﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RN.ERP.DAL.Context;
using RN.ERP.Entity.ZBDLRY;
using Fly.FlyCommon;
using Fly.Common.Linq;
using RN.ERP.DTO;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using Fly.Log;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using System.Configuration;

namespace RN.ERP.BLL.ZBDLRY
{
    public class OrderBLL : BaseOrderBLL
    {
        private ZBDL_Context dbContext
        {
            get
            {
                return (ZBDL_Context)base.baseContext;
            }
        }

        //private dbContext dbContext
        //{
        //    get
        //    {
        //        return new dbContext();
        //    }
        //}

        public OrderBLL()
        {
            base.baseContext = new ZBDL_Context();
        }

        #region CA订单及发票

        /// <summary>
        /// 获取订单列表。
        /// </summary>
        public override List<DTO.CaPayRelation> GetOrders(IList<QueryInvoiceInfoCondition> queryCondition, Guid userGuid, int pageCount, int pageSize)
        {
            var query = from ca in dbContext.CAPayInfo
                        join groupinfo in dbContext.GroupInfo 
                        on ca.GroupCode equals groupinfo.Code
                        join rela in dbContext.InvoiceOrderRelation 
                        on ca.KeyGUID equals rela.OrderGuid into carelas
                        from cainrela in carelas.DefaultIfEmpty()
                        join invo in dbContext.Invoice 
                        on cainrela.InvoiceGuid equals invo.KeyGuid into cainvoices
                        from cainvoice in cainvoices.DefaultIfEmpty()
                        where ca.CorpUserGuid == userGuid && (ca.IsDel == false || ca.IsDel == null)
                        select new DTO.CaPayRelation
                        {
                            ID = ca.ID,
                            KeyGUID = ca.KeyGUID,
                            iTitle = ca.iTitle,
                            CorpUserGuid = ca.CorpUserGuid,
                            AreaCode = ca.AreaCode,
                            LinkPerson = ca.LinkPerson,
                            SendAddress = ca.SendAddress,
                            officeTel = ca.officeTel,
                            mobileTel = ca.mobileTel,
                            postcode = ca.postcode,
                            RegisterDate = ca.RegisterDate,
                            bCAStatus = ca.bCAStatus,
                            Code = ca.Code,
                            SumPay = ca.SumPay,
                            GroupCode = ca.GroupCode,
                            FlowCode = ca.FlowCode,
                            GroupName = groupinfo.GroupName,
                            InvoiceGUID = cainvoice.KeyGuid,
                            InvoiceCode = cainvoice.InvoiceCode,
                            Notice = cainvoice.Notice,
                            InvoiceSumPay = cainvoice.SumPay,
                            InvoiceTitle = cainvoice.Title,
                            InvoiceLinkMan = cainvoice.LinkMan,
                            InvoiceMtel = cainvoice.Mtel,
                            InvoicePsCode = cainvoice.PsCode,
                            InvoiceSendAddress = cainvoice.SendAddress,
                            InvoiceTel = cainvoice.Tel,
                            InvoiceDate = cainvoice.InvoiceDate,
                            SendType = cainvoice.SendType,
                            TaxCode = cainvoice.TaxCode,
                            BankName = cainvoice.BankName,
                            BankCode = cainvoice.BankCode,
                            InvoiceOptType = cainvoice.InvoiceOptType,
                            InvoiceType = cainvoice.InvoiceType,
                            InvoiceStatus = cainvoice.InvoiceStatus,
                            InvoiceContent = cainvoice.InvoiceTitle,
                            CurrentAreaCode = ca.CurrentAreaCode
                        };
            query = query.BuildCondition<CaPayRelation>(queryCondition).OrderByDescending(m => m.InvoiceGUID)
                     .ThenBy(m => m.GroupCode).ThenByDescending(m => m.ID);
            if (pageSize > 0)
            {
                query = query.Skip(pageCount * pageSize).Take(pageSize);
            }
            var list = query.ToList();
            foreach (CaPayRelation item in list)
            {
                switch (item.bCAStatus.ToString())
                {
                    case "0":
                        item.StrStatus = "添加订单";
                        break;
                    case "1":
                        item.StrStatus = "提交订单";
                        break;
                    case "2":
                        item.StrStatus = "线下支付";
                        break;
                    case "3":
                        if (item.FlowCode.Contains("0,019,029,;4000"))
                        {
                            item.StrStatus = "财务确认";
                        }
                        else if (item.FlowCode.Contains("0,019,029,;4001"))
                        {
                            item.StrStatus = "主管审核";
                        }
                        else
                        {
                            item.StrStatus = "银联支付";
                        }
                        break;
                    case "4":
                        item.StrStatus = "已制Key";
                        break;
                    default:
                        item.StrStatus = "";
                        break;
                }
            }
            return list;
        }

        /// <summary>
        /// 获取订单数量。
        /// </summary>
        public override int GetOrderCount(IList<QueryInvoiceInfoCondition> queryCondition, Guid userGuid)
        {
            var query = from ca in dbContext.CAPayInfo
                        where ca.CorpUserGuid == userGuid && (ca.IsDel == false || ca.IsDel == null)
                        select ca;
            return query.BuildCondition<RN.ERP.Entity.ZBDLRY.tb_CAPayInfo>(queryCondition).Count();
        }

        /// <summary>
        /// 获取订单详细信息。
        /// </summary>
        public override CaPayInfo GetOrderInfo(string orderId)
        {
            CaPayInfo caPayInfo = new CaPayInfo();
            Guid orderGuid = Guid.Empty;
            if (Guid.TryParse(orderId, out orderGuid))
            {
                var query = from ca in dbContext.CAPayInfo
                            where ca.KeyGUID == orderGuid && (ca.IsDel == false || ca.IsDel == null)
                            select ca;
                Entity.ZBDLRY.tb_CAPayInfo payInfo = query.SingleOrDefault();
                if (payInfo != null)
                {
                    EntityHelper.ConvertEntity2OtherEntity(payInfo, caPayInfo);
                    int payInfoId = payInfo.ID;
                    var query1 = from caSub in dbContext.CAPayInfoSub
                                 join product in dbContext.ProductInfo on caSub.bCAKind equals product.Code
                                 where caSub.treeID == payInfoId && (caSub.IsDel == false || caSub.IsDel == null)
                                 select new CaPayInfoSub
                                 {
                                     ID = caSub.ID,
                                     KeyGUID = caSub.KeyGUID,
                                     treeID = caSub.treeID,
                                     Title = caSub.Title,
                                     SumPay = caSub.SumPay,
                                     SourceID = caSub.SourceID,
                                     Remark = caSub.Remark,
                                     FlowCode = caSub.FlowCode,
                                     bStatus = caSub.bStatus,
                                     Description = product.Description,
                                     bCAKind = caSub.bCAKind,
                                     bCAStatus = caSub.bCAStatus,
                                     Fee = product.Fee,
                                     YearlyFee = product.YearlyFee,
                                     FeeDescription = product.FeeDescription
                                 };
                    caPayInfo.PayInfoSub = query1.ToList();
                    return caPayInfo;
                }
            }
            return null;
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="payInfo"></param>
        /// <returns></returns>
        public override RN.ERP.DTO.OperationResult AddOrder(CaPayInfo payInfo)
        {
            OperationResult result = new OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    Entity.ZBDLRY.tb_CAPayInfo tbCaPayInfo = new Entity.ZBDLRY.tb_CAPayInfo();
                    EntityHelper.ConvertEntity2OtherEntity(payInfo, tbCaPayInfo);
                    dbContext.CAPayInfo.Add(tbCaPayInfo);
                    dbContext.SaveChanges();
                    var caid = from ca in dbContext.CAPayInfo
                               where ca.KeyGUID == payInfo.KeyGUID
                               select ca.ID;
                    payInfo.ID = caid.FirstOrDefault();
                    switch (payInfo.GroupCode.ToUpper())
                    {
                        case "CA01":
                            result = AddFirstOrder(payInfo);
                            break;
                        case "CA02":
                        case "CA03":
                        case "CA04":
                            result = AddOtherOrder(payInfo);
                            break;
                        default:
                            result = null;
                            break;
                    }
                    if (result != null && result.Result)
                    {
                        #region 添加操作日志
                        UserLogManager.Log(new User_Log()
                        {
                            Content = "添加订单",
                            ObjectId = payInfo.KeyGUID.ToString(),
                            IsrtUser = payInfo.CorpUserGuid.ToString(),
                            //IsrtUserName = "",
                            //IsrtUserArea = "",
                            FunctionId = "CA",
                            FunctionType = ((int)DTO.FuncType.Add).ToString(),
                            IsrtDate = payInfo.RegisterDate
                            //AppId = ""
                        });
                        #endregion
                        tran.Commit();
                    }
                    else
                    {
                        tran.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    result.Message = "添加失败：" + ex.Message;
                    result.Result = false;
                    tran.Rollback();
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 初始办理CA
        /// </summary>
        /// <param name="payInfo"></param>
        /// <returns></returns>
        private RN.ERP.DTO.OperationResult AddFirstOrder(CaPayInfo payInfo)
        {
            OperationResult result = new OperationResult();
            int count = 0;
            try
            {
                foreach (CaPayInfoSub item in payInfo.PayInfoSub)
                {
                    result = CheckVerify(item.bCAKind, payInfo.CorpUserGuid.ToString(), (int)item.SourceID);
                    if (!result.Result)
                    {
                        count = -1;
                        break;
                    }
                    item.treeID = payInfo.ID;
                    if (!CheckKey((int)item.SourceID, payInfo.CorpUserGuid, payInfo.GroupCode, payInfo.GroupCode))
                    {
                        Entity.ZBDLRY.tb_CAPayInfo_Sub tbCaPayInfoSub = new Entity.ZBDLRY.tb_CAPayInfo_Sub();
                        EntityHelper.ConvertEntity2OtherEntity(item, tbCaPayInfoSub);
                        dbContext.CAPayInfoSub.Add(tbCaPayInfoSub);
                    }
                    else
                    {
                        count++;
                        break;
                    }
                }
                if (count == 0)
                {
                    dbContext.SaveChanges();
                    result.Result = true;
                    result.Message = "添加成功！";
                }
                else if (count > 0)
                {
                    result.Message = "添加失败：一个企业(或个人)只能办理一次数字证书！";
                    result.Result = false;
                }
            }
            catch (Exception ex)
            {
                result.Message = "添加失败：" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 验证企业审核是否通过
        /// </summary>
        private RN.ERP.DTO.OperationResult CheckVerify(string bCAKind, string guid, int sourceid)
        {
            OperationResult result = new OperationResult();
            result.Result = true;
            Guid userguid = Guid.Empty;
            Guid.TryParse(guid, out userguid);
            var user = dbContext.T_Sys_Users.Where(m => m.UserGuid == userguid).FirstOrDefault();
            if (user != null)
            {
                if (bCAKind.StartsWith("C") || bCAKind.StartsWith("E"))
                {
                    if (user.RoleID != null && (user.RoleID == 101 || user.RoleID == 110))
                    {
                        return result;
                    }
                    else
                    {
                        int query1 = 0;
                        if (user.RoleID == 105)//招标企业
                        {
                            query1 = dbContext.Corp_CompanyInfos.Where(m => m.CorpUserGuid == userguid && m.FlowCode.StartsWith("1")).Count();
                        }
                        else
                        {
                            query1 = dbContext.FlowCodes.Where(m => m.ObjectId == guid && m.FlowCode.StartsWith("1")).Count();
                        }
                        if (query1 == 0)
                        {
                            result.Message = "添加失败：企业审核未通过，不能办理数字证书！";
                            result.Result = false;
                        }
                    }
                }
                else
                {
                    int query3 = 0;
                    var query2 = (from emp in dbContext.Emp_Manager
                                  join users in dbContext.T_Sys_Users on emp.CorpGuid equals users.UserGuid
                                  where emp.ID == sourceid
                                  select new { emp.EmpGuid, users.RoleID, emp.Name }).FirstOrDefault();
                    string empguid = query2.EmpGuid.ToString();
                    if (query2.RoleID != null && (query2.RoleID == 101 || query2.RoleID == 110))
                    {
                        return result;
                    }
                    else
                    {
                        if (user.RoleID == 105)
                        {
                            query3 = dbContext.Emp_ManagerZbRegister.Where(m => m.EmpGuid == query2.EmpGuid && m.OptFlag == 1
                                && m.bFlowStatus.StartsWith("1")).Count();
                        }
                        else
                        {
                            query3 = dbContext.FlowCodes.Where(m => m.ObjectId == empguid && m.FlowCode.StartsWith("1")).Count();
                        }
                        if (query3 == 0)
                        {
                            result.Message = "添加失败：人员" + query2.Name + "审核未通过，不能办理数字证书！";
                            result.Result = false;
                        }
                    }
                }
            }
            else
            {
                result.Message = "添加失败：企业不存在！";
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 添加其他类型订单
        /// </summary>
        private RN.ERP.DTO.OperationResult AddOtherOrder(CaPayInfo payInfo)
        {
            OperationResult result = new OperationResult();
            int count = 0;
            try
            {
                foreach (CaPayInfoSub item in payInfo.PayInfoSub)
                {
                    item.treeID = payInfo.ID;
                    if (CheckKey((int)item.SourceID, payInfo.CorpUserGuid, "CA01", null))
                    {
                        Entity.ZBDLRY.tb_CAPayInfo_Sub tbCaPayInfoSub = new Entity.ZBDLRY.tb_CAPayInfo_Sub();
                        EntityHelper.ConvertEntity2OtherEntity(item, tbCaPayInfoSub);
                        dbContext.CAPayInfoSub.Add(tbCaPayInfoSub);
                    }
                    else
                    {
                        count++;
                        break;
                    }
                }
                if (count == 0)
                {
                    dbContext.SaveChanges();
                    result.Result = true;
                    result.Message = "添加成功！";
                }
                else if (count > 0)
                {
                    result.Message = "添加失败：存在企业(或人员)没有办理数字证书！";
                    result.Result = false;
                }
            }
            catch (Exception ex)
            {
                result.Message = "添加失败：" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 获取产品列表
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public override List<DTO.tb_ProductInfo> GetProducts(List<ProductCondition> condition, string areacode)
        {
            var query = from product in dbContext.ProductInfo
                        where (string.IsNullOrEmpty(product.AreaCode) || product.AreaCode.StartsWith(areacode.Substring(0, 2)))
                        select new DTO.tb_ProductInfo
                        {
                            Id = product.Id,
                            KeyGuid = product.KeyGuid,
                            ProductCode = product.ProductCode,
                            Title = product.Title,
                            Code = product.Code,
                            Description = product.Description,
                            ValidateTo = product.ValidateTo,
                            IsrtDate = product.IsrtDate,
                            Roles = product.Roles,
                            Fee = product.Fee,
                            YearlyFee = product.YearlyFee,
                            FeeDescription = product.FeeDescription,
                            IsDel = product.IsDel,
                            GroupCode = product.GroupCode,
                            AreaCode = product.AreaCode,
                            SumPay = product.Fee
                        };
            if (condition.Count == 1 && ((condition[0].Code != null && condition[0].Code.V == "E25")))
            {
                return query.BuildCondition<DTO.tb_ProductInfo>(condition).ToList();
            }
            else
            {
                return query.Where(m => m.IsDel == false || m.IsDel == null).BuildCondition<DTO.tb_ProductInfo>(condition).ToList();
            }
        }

        /// <summary>
        /// 修改订单
        /// </summary>
        /// <param name="payInfo"></param>
        /// <returns></returns>
        public override OperationResult EditOrder(CaPayInfo payInfo)
        {
            OperationResult result = new OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    int count = 0;
                    var capay = dbContext.CAPayInfo.Where(c => c.KeyGUID == payInfo.KeyGUID).SingleOrDefault();
                    if (capay != null)
                    {
                        if (capay.bCAStatus == 0)
                        {
                            //capay.TransDate = payInfo.TransDate;
                            capay.OptDate = payInfo.OptDate;
                            capay.SumPay = payInfo.SumPay;
                            var newList = payInfo.PayInfoSub;
                            var oldList = dbContext.CAPayInfoSub.Where(c => c.treeID == capay.ID).ToList();
                            for (int i = 0; i < newList.Count; i++)
                            {
                                if (count != 0)
                                {
                                    break;
                                }
                                for (int j = 0; j < oldList.Count; j++)
                                {
                                    if (newList[i].SourceID == oldList[j].SourceID)
                                    {
                                        oldList[j].SumPay = newList[i].SumPay;
                                        oldList[j].bCAKind = newList[i].bCAKind;
                                        oldList[j].IsDel = false;
                                        break;
                                    }
                                    else if (j == oldList.Count - 1)
                                    {
                                        if ((!CheckKey((int)newList[i].SourceID, capay.CorpUserGuid, capay.GroupCode, "CA01") && capay.GroupCode == "CA01")
                                            || (CheckKey((int)newList[i].SourceID, capay.CorpUserGuid, "CA01", null) && capay.GroupCode != "CA01"))
                                        {
                                            newList[i].treeID = capay.ID;
                                            Entity.ZBDLRY.tb_CAPayInfo_Sub tbCaPayInfoSub = new Entity.ZBDLRY.tb_CAPayInfo_Sub();
                                            EntityHelper.ConvertEntity2OtherEntity(newList[i], tbCaPayInfoSub);
                                            dbContext.CAPayInfoSub.Add(tbCaPayInfoSub);
                                        }
                                        else
                                        {
                                            count++;
                                            break;
                                        }
                                    }
                                }
                            }
                            if (count == 0)
                            {
                                for (int i = 0; i < oldList.Count; i++)
                                {
                                    for (int j = 0; j < newList.Count; j++)
                                    {
                                        if (newList[j].SourceID == oldList[i].SourceID)
                                        {
                                            oldList[i].SumPay = newList[j].SumPay;
                                            oldList[i].bCAKind = newList[j].bCAKind;
                                            oldList[i].IsDel = false;
                                            break;
                                        }
                                        else if (j == newList.Count - 1)
                                        {
                                            oldList[i].IsDel = true;
                                        }
                                    }
                                }
                                dbContext.SaveChanges();
                                #region 添加操作日志
                                UserLogManager.Log(new User_Log()
                                {
                                    Content = "修改订单",
                                    ObjectId = payInfo.KeyGUID.ToString(),
                                    IsrtUser = capay.CorpUserGuid.ToString(),
                                    //IsrtUserName = "",
                                    //IsrtUserArea = "",
                                    FunctionId = "CA",
                                    FunctionType = ((int)DTO.FuncType.Edit).ToString(),
                                    IsrtDate = payInfo.OptDate
                                    //AppId = ""
                                });
                                #endregion
                                result.Result = true;
                                result.Message = "修改成功！";
                                tran.Commit();
                            }
                            else if (count > 0)
                            {
                                result.Message = capay.GroupCode == "CA01" ? "修改失败：一个企业(或个人)只能办理一次数字证书！" :
                                    "修改失败：存在企业(或人员)没有办理数字证书！";
                                result.Result = false;
                                tran.Rollback();
                            }
                        }
                        else
                        {
                            result.Result = false;
                            result.Message = "已提交订单不可修改！";
                        }
                    }
                    else
                    {
                        result.Result = false;
                        result.Message = "修改失败！";
                    }
                }
                catch (Exception ex)
                {
                    result.Message = "修改失败：" + ex.Message;
                    result.Result = false;
                    tran.Rollback();
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <returns></returns>
        public override OperationResult DeleteOrder(Guid orderGuid)
        {
            OperationResult result = new OperationResult();
            var delOrder = from ca in dbContext.CAPayInfo
                           where ca.KeyGUID == orderGuid
                           select ca;
            RN.ERP.Entity.ZBDLRY.tb_CAPayInfo caPayInfo = delOrder.FirstOrDefault();
            if (caPayInfo != null)
            {
                if (caPayInfo.bCAStatus == 0)
                {
                    caPayInfo.IsDel = true;
                    var list = dbContext.CAPayInfoSub.Where(c => c.treeID == caPayInfo.ID && (c.IsDel == false || c.IsDel == null)).ToList();
                    foreach (var item in list)
                    {
                        item.IsDel = true;
                    }
                    dbContext.SaveChanges();
                    #region 添加操作日志
                    UserLogManager.Log(new User_Log()
                    {
                        Content = "删除订单",
                        ObjectId = orderGuid.ToString(),
                        IsrtUser = caPayInfo.CorpUserGuid.ToString(),
                        //IsrtUserName = "",
                        //IsrtUserArea = "",
                        FunctionId = "CA",
                        FunctionType = ((int)DTO.FuncType.Del).ToString(),
                        IsrtDate = DateTime.Now
                        //AppId = ""
                    });
                    #endregion
                    result.Result = true;
                    result.Message = "删除成功！";
                }
                else
                {
                    result.Result = false;
                    result.Message = "已提交订单不可删除！";
                }
            }
            else
            {
                result.Result = false;
                result.Message = "删除失败！";
            }
            return result;
        }

        /// <summary>
        /// 生成订单。
        /// </summary>
        /// <returns></returns>
        public override OperationResult SubmitOrder(CaPayInfo payInfo)
        {
            OperationResult result = new OperationResult();
            try
            {
                var capay = dbContext.CAPayInfo.Where(c => c.KeyGUID == payInfo.KeyGUID).SingleOrDefault();
                if (capay != null)
                {
                    if (capay.bCAStatus == 0 || capay.bCAStatus == 1)
                    {
                        capay.iTitle = payInfo.iTitle;
                        capay.LinkPerson = payInfo.LinkPerson;
                        capay.SendAddress = payInfo.SendAddress;
                        capay.mobileTel = payInfo.mobileTel;
                        capay.officeTel = payInfo.officeTel;
                        capay.postcode = payInfo.postcode;
                        capay.bCAStatus = payInfo.bCAStatus;
                        capay.Notice = payInfo.Notice;
                        capay.TransDate = DateTime.Now;
                        capay.OptDate = payInfo.OptDate;
                        var list = dbContext.CAPayInfoSub.Where(c => c.treeID == capay.ID && (c.IsDel == false || c.IsDel == null)).ToList();
                        foreach (var item in list)
                        {
                            item.bCAStatus = payInfo.bCAStatus;
                        }
                        dbContext.SaveChanges();
                        #region 添加操作日志
                        UserLogManager.Log(new User_Log()
                        {
                            Content = capay.bCAStatus == 1 ? "银联支付" : "线下支付",
                            ObjectId = payInfo.KeyGUID.ToString(),
                            IsrtUser = capay.CorpUserGuid.ToString(),
                            //IsrtUserName = "",
                            //IsrtUserArea = "",
                            FunctionId = "CA",
                            FunctionType = ((int)DTO.FuncType.SubmitOrder).ToString(),
                            IsrtDate = payInfo.OptDate
                            //AppId = ""
                        });
                        #endregion
                        result.Result = true;
                        result.Message = "提交成功！";
                    }
                    else
                    {
                        result.Message = "该订单不可再次提交！";
                        result.Result = false;
                    }
                }
                else
                {
                    result.Message = "提交失败！";
                    result.Result = false;
                }
            }
            catch (Exception ex)
            {
                result.Message = "提交失败：" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 发票列表
        /// </summary>
        public override List<DTO.CaPayRelation> GetInvoicesList(IList<QueryInvoiceInfoCondition> queryCondition, int pageCount, int pageSize)
        {
            var query = GetInvoices();
            if (queryCondition.Count == 2 && ((queryCondition[0].bCAStatus != null && queryCondition[0].bCAStatus.V == 4) ||
                (queryCondition[queryCondition.Count - 1].bCAStatus != null && queryCondition[queryCondition.Count - 1].bCAStatus.V == 4)))
            {
                query = query.Where(m => m.InvoiceStatus == 0 || m.InvoiceStatus == 1);
                query = query.BuildCondition<CaPayRelation>(queryCondition).OrderBy(m => m.CorpUserGuid).ThenBy(m => m.InvoiceGUID);
            }
            else if (queryCondition[0].IsAudit != null)
            {
                query = query.BuildCondition<CaPayRelation>(queryCondition).OrderByDescending(m => m.RegisterDate);
            }
            else
            {
                query = query.BuildCondition<CaPayRelation>(queryCondition).OrderBy(m => m.CorpUserGuid).ThenBy(m => m.GroupCode).ThenByDescending(m => m.ID);
            }

            if (pageSize > 0)
            {
                query = query.Skip(pageCount * pageSize).Take(pageSize);
            }
            var list = query.ToList();
            foreach (CaPayRelation item in list)
            {
                switch (item.bCAStatus.ToString())
                {
                    case "0":
                        item.StrStatus = "添加订单";
                        break;
                    case "1":
                        item.StrStatus = "提交订单";
                        break;
                    case "2":
                        item.StrStatus = "线下支付";
                        break;
                    case "3":
                        if (item.FlowCode.Contains("0,019,029,;4000"))
                        {
                            item.StrStatus = "财务确认";
                        }
                        else if (item.FlowCode.Contains("0,019,029,;4001"))
                        {
                            item.StrStatus = "主管审核";
                        }
                        else
                        {
                            item.StrStatus = "银联支付";
                        }
                        break;
                    case "4":
                        item.StrStatus = "已制Key";
                        break;
                    default:
                        item.StrStatus = "";
                        break;
                }
            }
            return list;
        }

        /// <summary>
        /// 索要发票
        /// </summary>
        public override RN.ERP.DTO.OperationResult AddInvoices(InvoiceOrderRelation relation)
        {
            bool check = relation.InvoiceStatus != null && relation.InvoiceStatus == 0;
            OperationResult result = new OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    if (check)
                    {
                        string[] orderIds = relation.OrderIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        List<int> oIds = new List<int>();
                        foreach (string oId in orderIds)
                        {
                            int i = 0;
                            if (int.TryParse(oId, out i))
                            {
                                oIds.Add(i);
                            }
                        }
                        var query1 = from order in dbContext.CAPayInfo
                                     join rela in dbContext.InvoiceOrderRelation on order.KeyGUID equals rela.OrderGuid
                                     where (order.IsDel == false || order.IsDel == null) && oIds.Contains(order.ID)
                                     select order;
                        var query2 = from order in dbContext.CAPayInfo
                                     where (order.IsDel == false || order.IsDel == null) && oIds.Contains(order.ID)
                                     && order.bCAStatus != 3 && order.bCAStatus != 4
                                     select order;
                        int count = query1.Count();
                        int count2 = query2.Count();
                        if (count2 > 0)
                        {
                            result.Result = false;
                            result.Message = "索要发票失败：所选订单中，有" + count2 + "笔订单非财务确认！";
                        }
                        else if (count > 0)
                        {
                            result.Result = false;
                            result.Message = "索要发票失败：所选订单中，有" + count + "笔订单已开发票！";
                        }
                        else
                        {
                            if (relation.KeyGuid == null || relation.KeyGuid == Guid.Empty)
                            {
                                relation.KeyGuid = Guid.NewGuid();
                            }
                            Entity.ZBDLRY.Tb_Invoice tbInvoice = new Entity.ZBDLRY.Tb_Invoice();
                            EntityHelper.ConvertEntity2OtherEntity(relation, tbInvoice);
                            dbContext.Invoice.Add(tbInvoice);
                            dbContext.SaveChanges();
                            var query = from order in dbContext.CAPayInfo
                                        where oIds.Contains(order.ID) && (order.IsDel == false || order.IsDel == null)
                                        select order;
                            string code = query.FirstOrDefault().GroupCode;
                            foreach (Entity.ZBDLRY.tb_CAPayInfo caOrder in query.ToList())
                            {
                                if (caOrder.GroupCode == code)
                                {
                                    Entity.ZBDLRY.Tb_InvoiceOrderRelation tbInvoiceOrderRelation = new Entity.ZBDLRY.Tb_InvoiceOrderRelation()
                                    {
                                        InvoiceGuid = relation.KeyGuid,
                                        OrderGuid = caOrder.KeyGUID,
                                        RelationType = 0
                                    };
                                    dbContext.InvoiceOrderRelation.Add(tbInvoiceOrderRelation);
                                }
                                else
                                {
                                    code = string.Empty;
                                    break;
                                }
                            }

                            if (code == string.Empty)
                            {
                                result.Result = false;
                                result.Message = "索要发票失败：不同类型订单不可一起索要发票！";
                                tran.Rollback();
                            }
                            else
                            {
                                dbContext.SaveChanges();
                                #region 添加操作日志
                                UserLogManager.Log(new User_Log()
                                {
                                    Content = "索要发票",
                                    ObjectId = relation.KeyGuid.ToString(),
                                    IsrtUser = relation.IsrtUser,
                                    IsrtUserName = relation.IsrtUserName,
                                    //IsrtUserArea = "",
                                    FunctionId = "CA",
                                    FunctionType = ((int)DTO.FuncType.GetInvoices).ToString(),
                                    IsrtDate = relation.IsrtDate
                                    //AppId = ""
                                });
                                #endregion
                                result.Result = true;
                                result.Message = "索要发票成功！";
                            }
                        }
                    }
                    else
                    {
                        var invo = dbContext.Invoice.Where(m => m.InvoiceCode == relation.InvoiceCode).FirstOrDefault();
                        if (invo == null)
                        {
                            var invoices = dbContext.Invoice.Where(m => m.KeyGuid == relation.KeyGuid).FirstOrDefault();
                            if (invoices != null && invoices.InvoiceStatus == 0)
                            {
                                invoices.InvoiceStatus = 1;
                                invoices.InvoiceCode = relation.InvoiceCode;
                                invoices.InvoiceDate = relation.InvoiceDate;
                                invoices.UpdateDate = relation.UpdateDate;
                                invoices.UpdateUser = relation.UpdateUser;
                                invoices.UpdateUserName = relation.UpdateUserName;
                                dbContext.SaveChanges();
                                #region 添加操作日志
                                UserLogManager.Log(new User_Log()
                                {
                                    Content = "开具发票",
                                    ObjectId = relation.KeyGuid.ToString(),
                                    IsrtUser = relation.UpdateUser,
                                    IsrtUserName = relation.UpdateUserName,
                                    //IsrtUserArea = "",
                                    FunctionId = "CA",
                                    FunctionType = ((int)DTO.FuncType.AddInvoices).ToString(),
                                    IsrtDate = relation.UpdateDate
                                    //AppId = ""
                                });
                                #endregion
                                result.Result = true;
                                result.Message = "开发票成功！";
                            }
                            else
                            {
                                result.Result = false;
                                result.Message = "开发票失败！";
                            }
                        }
                        else
                        {
                            result.Result = false;
                            result.Message = "开发票失败：发票编号不能重复！";
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    result.Message = check ? "索要发票失败：" + ex.Message : "开发票失败：" + ex.Message;
                    result.Result = false;
                    tran.Rollback();
                }
            }
            return result;
        }

        public override int GetInvoicesCount(IList<QueryInvoiceInfoCondition> queryCondition)
        {
            var query = GetInvoices();
            if (queryCondition.Count == 2 && ((queryCondition[0].bCAStatus != null && queryCondition[0].bCAStatus.V == 4) ||
                (queryCondition[queryCondition.Count - 1].bCAStatus != null && queryCondition[queryCondition.Count - 1].bCAStatus.V == 4)))
            {
                query = query.Where(m => m.InvoiceStatus == 0 || m.InvoiceStatus == 1);
            }
            return query.BuildCondition<CaPayRelation>(queryCondition).Count();
        }

        private IQueryable<DTO.CaPayRelation> GetInvoices()
        {
            var query = from ca in dbContext.CAPayInfo
                        join groupinfo in dbContext.GroupInfo on ca.GroupCode equals groupinfo.Code
                        join rela in dbContext.InvoiceOrderRelation on ca.KeyGUID equals rela.OrderGuid into carelas
                        from cainrela in carelas.DefaultIfEmpty()
                        join invo in dbContext.Invoice on cainrela.InvoiceGuid equals invo.KeyGuid into cainvoices
                        from cainvoice in cainvoices.DefaultIfEmpty()
                        join sub in dbContext.CAPayInfoSub on ca.ID equals sub.treeID
                        join pro in dbContext.ProductInfo on sub.bCAKind equals pro.Code
                        where (ca.IsDel == false || ca.IsDel == null) && (sub.IsDel == false || sub.IsDel == null)
                        select new DTO.CaPayRelation
                        {
                            ID = ca.ID,
                            KeyGUID = ca.KeyGUID,
                            CorpName = ca.iTitle,
                            iTitle = ca.iTitle,
                            Title = sub.Title,
                            CorpUserGuid = ca.CorpUserGuid,
                            AreaCode = ca.AreaCode,
                            LinkPerson = ca.LinkPerson,
                            SendAddress = ca.SendAddress,
                            officeTel = ca.officeTel,
                            mobileTel = ca.mobileTel,
                            postcode = ca.postcode,
                            RegisterDate = ca.RegisterDate,
                            RegisterDate1 = ca.RegisterDate,
                            bCAStatus = ca.bCAStatus,
                            Code = ca.Code,
                            GroupCode = ca.GroupCode,
                            FlowCode = ca.FlowCode,
                            Sum = ca.SumPay,
                            SumPay = sub.SumPay,
                            bCAKind = pro.Title,
                            ProCode = pro.Code,
                            IsAudit = pro.IsAudit,
                            GroupName = groupinfo.GroupName,
                            InvoiceGUID = cainvoice.KeyGuid,
                            InvoiceCode = cainvoice.InvoiceCode,
                            Notice = cainvoice.Notice,
                            InvoiceSumPay = cainvoice.SumPay,
                            InvoiceTitle = cainvoice.Title,
                            InvoiceLinkMan = cainvoice.LinkMan,
                            InvoiceMtel = cainvoice.Mtel,
                            InvoicePsCode = cainvoice.PsCode,
                            InvoiceSendAddress = cainvoice.SendAddress,
                            InvoiceTel = cainvoice.Tel,
                            InvoiceDate = cainvoice.InvoiceDate,
                            SendType = cainvoice.SendType,
                            TaxCode = cainvoice.TaxCode,
                            BankName = cainvoice.BankName,
                            BankCode = cainvoice.BankCode,
                            InvoiceOptType = cainvoice.InvoiceOptType,
                            InvoiceType = cainvoice.InvoiceType,
                            InvoiceStatus = cainvoice.InvoiceStatus,
                            InvoiceContent = cainvoice.InvoiceTitle,
                            IsrtDate = cainvoice.IsrtDate,
                            AreaCode1 = ca.AreaCode,
                            CurrentAreaCode = ca.CurrentAreaCode
                        };
            return query;
        }

        /// <summary>
        /// 验证是否存在Key
        /// </summary>
        /// <param name="sourceId"></param>
        /// <param name="userGuid"></param>
        /// <param name="groupCode"></param>
        /// <returns></returns>
        private bool CheckKey(int sourceId, Guid userGuid, string groupCode, string Code)
        {
            var query = from capay in dbContext.CAPayInfo
                        join sub in dbContext.CAPayInfoSub on capay.ID equals sub.treeID
                        join pro in dbContext.ProductInfo on sub.bCAKind equals pro.Code
                        where capay.CorpUserGuid == userGuid && sub.SourceID == sourceId && (capay.IsDel == false || capay.IsDel == null)
                        && (sub.IsDel == false || sub.IsDel == null)
                        && capay.GroupCode == groupCode
                        select new { sub.bCAKind, sub.bCAStatus };
            if (query.FirstOrDefault() != null)
            {
                string cakind = query.FirstOrDefault().bCAKind;
                if (!string.IsNullOrEmpty(Code) && Code == "CA01")//初始办理，有数据
                {
                    return true;
                }
                else if (groupCode == "CA01")//非初始办理验证是否已制过key
                {
                    if (query.Where(m => m.bCAStatus == 4).Count() <= 0)
                    {
                        return false;
                    }
                }
                if (cakind.StartsWith("C") || cakind.StartsWith("E"))//初始办理已制过key，验证是否有狗号
                {
                    var query1 = from users in dbContext.T_Sys_Users
                                 where users.UserGuid == userGuid
                                 select users.DogID;
                    return query1.FirstOrDefault() > 0;
                }
                else
                {
                    var query2 = from emp in dbContext.Emp_Manager
                                 where emp.ID == sourceId && emp.CorpGuid == userGuid
                                 select emp.empdogid;
                    return query2.FirstOrDefault() > 0;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 企业CA申请表下载
        /// </summary>
        /// <param name="corpUserGuid"></param>
        /// <returns></returns>
        public override byte[] GetCorpCAPdf(Guid corpUserGuid)
        {
            var CI = dbContext.Corp_CompanyInfos.FirstOrDefault(m => m.CorpUserGuid == corpUserGuid);
            var user = dbContext.T_Sys_Users.FirstOrDefault(m => m.UserGuid == corpUserGuid);
            var FaRen = dbContext.Emp_Manager.FirstOrDefault(m => m.CorpGuid == corpUserGuid && m.TypeFlag.Contains("3") &&
                (m.IsDel == false || m.IsDel == null));
            var Quals = dbContext.Corp_CompanyQualities.Where(m => m.CorpUserGuid == corpUserGuid && (m.IsDel == false || m.IsDel == null)).
                OrderByDescending(m => m.IsMain);
            if (CI == null || user == null || FaRen == null || Quals == null)
            {
                return null;
            }
            tb_Emp_Manager_Zbdl linkman = new tb_Emp_Manager_Zbdl();
            if (user.RoleID == 105)
            {
                linkman = dbContext.Emp_Manager.FirstOrDefault(m => m.CorpGuid == corpUserGuid && m.TypeFlag.Contains("9"));
            }
            Document doc1 = new Document(PageSize.A4, 60, 60, 20, 40);
            using (MemoryStream Memory = new MemoryStream())
            {
                PdfWriter PdfWriter = PdfWriter.GetInstance(doc1, Memory);

                BaseFont bfChinese = BaseFont.CreateFont(@"C:\windows\fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font Font22 = new Font(bfChinese, 22);
                Font Font18 = new Font(bfChinese, 18);
                Font Font16 = new Font(bfChinese, 16);
                Font Font14 = new Font(bfChinese, 14);
                Font Font12 = new Font(bfChinese, 12);
                Font Font12Bold = new Font(bfChinese, 12, Font.BOLD);
                Font Font10 = new Font(bfChinese, 10);
                Font Font12Italic = new Font(bfChinese, 12, Font.BOLDITALIC);
                Font Font10Bold = new Font(bfChinese, 10, Font.BOLD);
                Paragraph parag;
                Chunk chunk;

                doc1.Open();
                doc1.AddAuthor("青岛福莱易通软件有限公司 http://www.flyedt.com");
                doc1.AddTitle(CI.CorpName + " 数字证书申请表");
                doc1.Add(new Paragraph("山东省建设工程招标投标监管信息系统", Font12));
                parag = new Paragraph("企 业 数 字 证 书 及 电 子 印 章 申 请 表", Font18);
                parag.Alignment = Element.ALIGN_CENTER;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(20f, 1f);
                parag.Add(new Chunk("以下信息由申请单位填写  ", Font12Italic));
                parag.Add(new Chunk("请用签字笔如实、准确、清楚地填写，并加盖单位公章", new Font(bfChinese, 8)));
                parag.Add(new Chunk("      " + DateTime.Now.ToLongDateString(), Font12));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(1f, 1f);
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(1, 5);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                #region 单位信息
                parag = new Paragraph();
                parag.SetLeading(1f, 1.2f);
                parag.Add(new Chunk("单位名称（全称）：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 65).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 17).ToString() + CI.CorpName, Font12));//"青岛建工集团"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.4f);
                parag.Add(new Chunk("组织机构代码：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 18).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("   工商注册代码：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 18).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 16).ToString() + CI.OrginazationCode, Font12));//"16890456-X"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 58).ToString() + CI.BussinessNum, Font12));//3702022288117611
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.4f);
                parag.Add(new Chunk("单位地址：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 77).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 10).ToString() + CI.Address, Font12));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.4f);
                parag.Add(new Chunk("邮政编码：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 12).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  电子邮箱：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 50).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.4f);
                string pcode = CI.ZipCode;//"266888";
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 12).ToString() + pcode, new Font(bfChinese, 12)));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 40).ToString() + CI.Email, Font10));//"aliBABA_aliBABA_aliBABA@sina.com.cn.COM.CN.COM.CN"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.4f);
                parag.Add(new Chunk("传   真：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 25).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("             ", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                //chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 12).ToString() + CI.Fax, Font12));//"86 532 88776655166"
                doc1.Add(parag);

                //parag = new Paragraph();
                //parag.SetLeading(-17f, 1.4f);
                //parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 52).ToString() + CI.Fax, Font12));//"86 532 887766551"
                //doc1.Add(parag);
                #endregion 单位信息

                #region 法人信息
                parag = new Paragraph(new StringBuilder().Insert(0, "- ", 45).ToString().Trim(), Font10Bold);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.4f);
                parag.Add(new Chunk("法定代表人：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 28).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                //parag.Add(new Chunk("  手   机：", Font10));
                //chunk = new Chunk(new StringBuilder().Insert(0, " ", 18).ToString(), Font10);
                //chunk.SetUnderline(0, -2);
                //parag.Add(chunk);
                parag.Add(new Chunk("    电   话：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 12).ToString() + FaRen.Name, new Font(bfChinese, 12)));//"赵钱孙里"
                doc1.Add(parag);

                //parag = new Paragraph();
                //parag.SetLeading(-17f, 1.4f);
                //parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 37).ToString() + FaRenExt.MobilePhone, Font12));//"0 13333333333"
                //doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-16f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 52).ToString() + FaRen.Tel, Font12));//"86 532 887766551"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.4f);
                parag.Add(new Chunk("证件类型：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    证件号码：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-17f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 12).ToString() + GetIdType(FaRen.IDType), Font12));//"有关部门工作证"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-16f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 52).ToString() + FaRen.IDCard, Font12));//"370202234567890078X"
                doc1.Add(parag);
                #endregion 法人信息

                #region 联系人信息
                parag = new Paragraph();
                parag.SetLeading(4f, 1.4f);
                parag.Add(new Chunk("联系人姓名：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 28).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    联系电话：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-17f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 12).ToString() + (user.RoleID == 105 && linkman != null ? linkman.Name : CI.LinkMan1), Font12));//"齐天大圣"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-16f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 52).ToString() + (user.RoleID == 105 && linkman != null ? linkman.Tel : CI.Tel), Font12));//"DH370202234567890078X"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.4f);
                parag.Add(new Chunk("证件类型：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    证件号码：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-17f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 12).ToString() + (user.RoleID == 105 && linkman != null ? GetIdType(linkman.IDType) : GetIdType(CI.CertificateType.ToString())), Font12));//"无关部门工作证"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-16f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 52).ToString() + (user.RoleID == 105 && linkman != null ? linkman.IDCard : CI.CertificateNumber), Font12));//"370202234567890078X"
                doc1.Add(parag);

                #endregion 联系人信息

                parag = new Paragraph(new StringBuilder().Insert(0, "- ", 45).ToString().Trim(), Font10Bold);
                PdfPTable table;

                #region 受托办理人
                parag = new Paragraph("我单位委托以下人员办理数字证书事宜（请手工填写）", new Font(bfChinese, 12, Font.BOLD));
                parag.SetLeading(5f, 1.4f);
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1.6f);
                parag.Add(new Chunk("受托办理人：", new Font(bfChinese, 10, Font.BOLD)));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 12).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  证件类型：", new Font(bfChinese, 10, Font.BOLD)));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 12).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  证件号码：", new Font(bfChinese, 10, Font.BOLD)));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);
                #endregion 受托办理人

                #region 签章留存
                parag = new Paragraph(new StringBuilder().Insert(0, "- ", 45).ToString().Trim(), Font10Bold);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1f);
                parag.Add(new Chunk("签章留存处：", Font16));
                doc1.Add(parag);
                parag = new Paragraph();
                parag.SetLeading(5f, 1f);
                parag.Add(new Chunk("    下述三个印章（签名）将作为电子签章的图形基础，将出现在所有经电子签章认证的电子文件中，所以请认真加盖，保持印章完整、清晰、无虚影；务必由法定代表人本人签字。", Font10));
                doc1.Add(parag);
                parag = new Paragraph();
                parag.SetLeading(5f, 1f);
                parag.Add(new Chunk("    《电子签名法》第二十七条规定“未向电子认证服务提供者提供真实、完整和准确的信息，或者有其他过错，给电子签名依赖方、电子认证服务提供者造成损失的，承担赔偿责任。”", Font10));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(2f, 1f);
                parag.Add(new Chunk(" ", new Font(bfChinese, 5)));
                doc1.Add(parag);

                table = new PdfPTable(new float[] { 5, 3, 3 });
                table.WidthPercentage = 100f;

                table.AddCell(new Phrase("单位公章：\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", Font12));
                table.AddCell(new Phrase("法定代表人名章：", Font12));
                table.AddCell(new Phrase("法定代表人签字：", Font12));
                doc1.Add(table);
                #endregion 签章留存

                parag = new Paragraph();
                parag.SetLeading(-54f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 60).ToString() + "申请日期：", Font12));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1.2f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 63).ToString() + DateTime.Now.ToLongDateString(), Font12));
                doc1.Add(parag);

                parag = new Paragraph("以下信息由数字证书发放点填写", Font12Italic);
                parag.SetLeading(25f, 1.4f);
                doc1.Add(parag);
                parag = new Paragraph();
                parag.SetLeading(1f, 1f);
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(1, 5);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.6f);
                parag.Add(new Chunk("资料审核人签名：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    日期：      年    月    日", Font10));
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.6f);
                parag.Add(new Chunk("发放 E-Key 编号：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 65).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.6f);
                parag.Add(new Chunk("受托办理人签名：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    日期：      年    月    日", Font10));
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 2.6f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 80).ToString() + "本表一式两份", Font10));
                doc1.Add(parag);

                // 协议页
                doc1.NewPage();
                doc1.Add(new Paragraph("山东省建设工程招标投标监管信息系统", Font12));
                parag = new Paragraph("企 业 数 字 证 书 及 电 子 印 章 使 用 协 议", Font16);
                parag.Alignment = Element.ALIGN_CENTER;
                doc1.Add(parag);
                parag = new Paragraph(" ", Font10);
                doc1.Add(parag);
                parag = new Paragraph("甲方：" + CI.CorpName, Font12Bold);
                doc1.Add(parag);
                parag = new Paragraph();
                parag.SetLeading(-12f, 1.0f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, "　", 24).ToString() + "乙方：青岛福莱易通软件有限公司", Font12Bold));
                //parag = new Paragraph("乙方：青岛福莱易通软件有限公司", Font12Bold);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);

                using (StreamReader sr1 = new StreamReader(File.OpenRead(AppDomain.CurrentDomain.BaseDirectory + "LoadFiles\\corpagreement.txt")))
                {
                    while (sr1.Peek() >= 0)
                    {
                        parag = new Paragraph();
                        parag.SetLeading(-1f, 1.0f);
                        parag.Add(new Chunk(sr1.ReadLine(), Font10));
                        doc1.Add(parag);
                    }
                }
                //资质附表
                doc1.NewPage();

                #region 资质信息
                //doc1.Add(new Paragraph("烟台市建筑市场诚信体系建管平台 - 用户中心", Font12));
                //parag = new Paragraph("企 业 资 质 登 记 表", Font16);
                //parag.Alignment = Element.ALIGN_CENTER;
                //doc1.Add(parag);

                //table = new PdfPTable(new float[] { 5, 2, 2, 2 });

                //parag = new Paragraph();
                //parag.SetLeading(2f, 1f);
                //parag.Add(new Chunk(DateTime.Now.ToLongDateString(), Font12));
                //parag.Alignment = Element.ALIGN_RIGHT;
                //doc1.Add(parag);

                //parag = new Paragraph();
                //parag.SetLeading(2f, 1f);
                //parag.Add(new Chunk(" ", new Font(bfChinese, 10)));
                //doc1.Add(parag);

                //parag = new Paragraph("    请仔细核对资质信息是否完整、准确，如不完整或信息发生变化时，请及时与数字证书管理机构联系。电子招投标中的资质信息均来源于本表。", Font10);
                //doc1.Add(parag);

                //parag = new Paragraph();
                //parag.SetLeading(2f, 1f);
                //parag.Add(new Chunk(" ", new Font(bfChinese, 5)));
                //doc1.Add(parag);

                //parag = new Paragraph();
                //parag.SetLeading(4f, 1.6f);
                //parag.Add(new Chunk("资质证书正本编号：", Font12));
                //chunk = new Chunk(CI.PassNum, Font12);
                ////chunk.SetUnderline(0, -2);
                //parag.Add(chunk);
                ////parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                //doc1.Add(parag);

                //parag = new Paragraph();
                //parag.SetLeading(2f, 1f);
                //parag.Add(new Chunk(" ", new Font(bfChinese, 5)));
                //doc1.Add(parag);

                //table.WidthPercentage = 100f;
                ////string[] PdfTitleField = PDFFieldName.Split(',');
                //foreach (string tit in "资质名称,资质等级,有效期自,有效期到".Split(','))
                //{
                //    if (!string.IsNullOrEmpty(tit))
                //        table.AddCell(new Phrase(tit, Font10Bold));
                //}

                //foreach (var qual in Quals)
                //{
                //    //table.AddCell(new Phrase(qual.IsMain ? "√" : "", Font10));
                //    table.AddCell(new Phrase(qual.DetailName + (qual.IsMain ? "(主项资质)" : ""), Font10));//"造价咨询"
                //    table.AddCell(new Phrase(qual.GradeName, Font10));//"甲级"

                //    //table.AddCell(new Phrase(qual.QualityCode, Font10));//"2012-5-1"
                //    table.AddCell(new Phrase(qual.GetDate.HasValue ? qual.GetDate.Value.ToString("yyyy-MM-dd") : "", Font10));//"38438453"

                //    table.AddCell(new Phrase(qual.zzzEndDate.HasValue ? qual.zzzEndDate.Value.ToString("yyyy-MM-dd") : "", Font10));//"2012-5-31"
                //}


                //doc1.Add(table);
                #endregion 资质信息

                #region 所需材料
                parag = new Paragraph(" ", Font16);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font16);
                doc1.Add(parag);
                parag = new Paragraph("企业申办数字证书所需递交（寄送）材料：", Font16);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("1、《企业数字证书申请表》及《企业数字证书使用协议》（盖章、签字、一式两份）", Font14);
                doc1.Add(parag);
                parag = new Paragraph("2、企业资质证书副本复印件（加盖公章）", Font14);
                doc1.Add(parag);
                parag = new Paragraph("3、营业执照副本复印件（加盖公章）", Font14);
                doc1.Add(parag);
                parag = new Paragraph("4、组织机构代码证副本复印件（加盖公章）", Font14);
                doc1.Add(parag);
                parag = new Paragraph("5、税务登记证副本复印件（加盖公章）", Font14);
                doc1.Add(parag);
                parag = new Paragraph("6、法定代表人身份证明复印件（加盖公章）", Font14);
                doc1.Add(parag);
                parag = new Paragraph("7、经办人身份证明复印件（加盖公章）", Font14);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font16);
                doc1.Add(parag);
                parag = new Paragraph("用户可自行选择网上支付或银行汇款，支付办理费用", new Font(bfChinese, 16, Font.ITALIC));
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("汇款信息", Font16);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("名  称：青岛福莱易通软件有限公司", Font14);
                doc1.Add(parag);
                parag = new Paragraph("开户行：交行青岛宁夏路第一支行", Font14);
                doc1.Add(parag);
                parag = new Paragraph("账  号：37200 5522 0180 1004 4812", Font14);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("联系方式", Font16);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("地  址：青岛市市南区宁夏路288号 青岛软件园1号楼1702", Font14);
                doc1.Add(parag);
                parag = new Paragraph("邮  编：266071", Font14);
                doc1.Add(parag);
                parag = new Paragraph("总  机：0532 - 85871505", Font14);
                doc1.Add(parag);
                #endregion 所需材料

                doc1.Close();
                return Memory.GetBuffer();
            }
        }

        /// <summary>
        /// 个人CA申请表下载
        /// </summary>
        /// <param name="empGuid"></param>
        /// <returns></returns>
        public override byte[] GetPsnCAPdf(Guid empGuid)
        {
            var EI = dbContext.Emp_Manager.FirstOrDefault(m => m.EmpGuid == empGuid);
            var Titles = dbContext.Emp_Qualities.Where(q => q.EmpGuid == empGuid && (q.IsDel == false || q.IsDel == null));
            if (EI == null || Titles == null)
            {
                return null;
            }
            Document doc1 = new Document(PageSize.A4, 60, 60, 20, 40);
            using (MemoryStream Memory = new MemoryStream())
            {
                PdfWriter PdfWriter = PdfWriter.GetInstance(doc1, Memory);

                BaseFont bfChinese = BaseFont.CreateFont(@"C:\windows\fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font Font22 = new Font(bfChinese, 22);
                Font Font18 = new Font(bfChinese, 18);
                Font Font16 = new Font(bfChinese, 16);
                Font Font14 = new Font(bfChinese, 14);
                Font Font12 = new Font(bfChinese, 12);
                Font Font12Bold = new Font(bfChinese, 12, Font.BOLD);
                Font Font10 = new Font(bfChinese, 10);
                Font Font12Italic = new Font(bfChinese, 12, Font.BOLDITALIC);
                Font Font10Bold = new Font(bfChinese, 10, Font.BOLD);
                Paragraph parag;
                Phrase phrase;
                Chunk chunk;

                doc1.Open();
                doc1.AddAuthor("青岛福莱易通软件有限公司 http://www.flyedt.com");
                doc1.AddTitle(EI.Name + " 数字证书申请表");
                doc1.Add(new Paragraph("山东省建设工程招标投标监管信息系统", Font12));
                parag = new Paragraph("个 人 数 字 证 书 及 电 子 印 章 申 请 表", Font18);
                parag.Alignment = Element.ALIGN_CENTER;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(25f, 1f);
                parag.Add(new Chunk("以下信息由申请人填写  ", Font12Italic));
                parag.Add(new Chunk("请用签字笔如实、准确、清楚地填写，并本人签字并加盖人名章", new Font(bfChinese, 8)));
                parag.Add(new Chunk("    " + DateTime.Now.ToLongDateString(), Font12));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(1f, 1f);
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(1, 5);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                #region 个人信息

                parag = new Paragraph();
                parag.SetLeading(5f, 1.5f);
                parag.Add(new Chunk("姓  名：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 20).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  性  别：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 5).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  出生日期：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 20).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 11).ToString() + EI.Name, new Font(bfChinese, 12)));//"赵钱孙里"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 41).ToString() + (EI.Sex == 0 ? "女" : "男"), Font12));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 60).ToString() + (EI.Birthday.HasValue ? EI.Birthday.Value.ToString("yyyy-MM-dd") : ""), Font12));//"2002年11月12日"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1.5f);
                parag.Add(new Chunk("手  机：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 10).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  电  话：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 13).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  电子邮箱：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 27).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 9).ToString() + EI.MobileTel, new Font(bfChinese, 10)));//13355555555
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 33).ToString() + EI.Tel, Font10));//"0564 87651463"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 62).ToString() + EI.EMail, Font10));//ayayayaya.bongbong@sina.com.cn
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1.5f);
                parag.Add(new Chunk("证件类型：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    证件号码：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 12).ToString() + GetIdType(EI.IDType), Font12));//有关部门工作证
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 52).ToString() + EI.IDCard, Font12));//"370202234567890078X"
                doc1.Add(parag);

                #endregion 个人信息

                #region 证书信息
                parag = new Paragraph(new StringBuilder().Insert(0, "- ", 45).ToString().Trim(), Font10Bold);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(2f, 1.5f);
                parag.Add(new Chunk("证书信息：", Font12));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(2f, 1f);
                parag.Add(new Chunk(" ", new Font(bfChinese, 5)));
                doc1.Add(parag);

                PdfPTable table = new PdfPTable(4);

                table.WidthPercentage = 100f;
                //string[] PdfTitleField = PDFFieldName.Split(',');
                foreach (string tit in "类别,证书号,专业,签发日期".Split(','))
                {
                    if (!string.IsNullOrEmpty(tit))
                        table.AddCell(new Phrase(tit, Font10));
                }

                foreach (var title in Titles)
                {
                    table.AddCell(new Phrase(title.CertificateName, Font10));
                    table.AddCell(new Phrase(title.CertificateCode, Font10));
                    table.AddCell(new Phrase(title.CSCode, Font10));
                    table.AddCell(new Phrase(title.GetCertificateDate.HasValue ? title.GetCertificateDate.Value.ToString("yyyy-MM-dd") : "", Font10));
                }

                //table.AddCell(new Phrase("造价咨询", Font10));
                //table.AddCell(new Phrase("38438453", Font10));
                //table.AddCell(new Phrase("2012-5-1", Font10));
                //table.AddCell(new Phrase("2012-5-31", Font10));
                //table.AddCell(new Phrase(" ", Font10));
                //table.AddCell(new Phrase("38438453", Font10));
                //table.AddCell(new Phrase("2012-5-1", Font10));
                //table.AddCell(new Phrase("2012-5-31", Font10));
                //table.AddCell(new Phrase(" ", Font10));
                //table.AddCell(new Phrase("38438453", Font10));
                //table.AddCell(new Phrase("2012-5-1", Font10));
                //table.AddCell(new Phrase("2012-5-31", Font10));
                doc1.Add(table);
                #endregion 证书信息

                parag = new Paragraph(new StringBuilder().Insert(0, "- ", 45).ToString().Trim(), Font10Bold);

                #region 受托办理人
                parag = new Paragraph("申请人委托以下人员办理数字证书事宜（请手工填写）", new Font(bfChinese, 12, Font.BOLD));
                parag.SetLeading(5f, 1.4f);
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1.6f);
                parag.Add(new Chunk("受托办理人：", new Font(bfChinese, 10, Font.BOLD)));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 12).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  证件类型：", new Font(bfChinese, 10, Font.BOLD)));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 12).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  证件号码：", new Font(bfChinese, 10, Font.BOLD)));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);
                #endregion 受托办理人

                #region 签章留存
                parag = new Paragraph(new StringBuilder().Insert(0, "- ", 45).ToString().Trim(), Font10Bold);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1f);
                parag.Add(new Chunk("签章留存处：", Font16));
                doc1.Add(parag);
                parag = new Paragraph();
                parag.SetLeading(5f, 1f);
                parag.Add(new Chunk("    下述印章（签名）将作为电子签章的图形基础，将出现在所有经电子签章认证的电子文件中，所以请认真加盖，保持印章完整、清晰、无虚影；务必由申请人本人签字。", Font10));
                doc1.Add(parag);
                parag = new Paragraph();
                parag.SetLeading(5f, 1f);
                parag.Add(new Chunk("    《电子签名法》第二十七条规定“未向电子认证服务提供者提供真实、完整和准确的信息，或者有其他过错，给电子签名依赖方、电子认证服务提供者造成损失的，承担赔偿责任。”", Font10));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(2f, 1f);
                parag.Add(new Chunk(" ", new Font(bfChinese, 5)));
                doc1.Add(parag);

                table = new PdfPTable(2);
                table.WidthPercentage = 70f;

                table.AddCell(new Phrase("申请人印章：\r\n(资格专用章)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", Font12));
                table.AddCell(new Phrase("申请人签字：", Font12));
                doc1.Add(table);
                #endregion 签章留存

                parag = new Paragraph();
                parag.SetLeading(-54f, 1.4f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 50).ToString() + "申请日期：", Font12));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1.2f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 53).ToString() + DateTime.Now.ToLongDateString(), Font12));
                doc1.Add(parag);

                parag = new Paragraph("以下信息由数字证书发放点填写", Font12Italic);
                parag.SetLeading(25f, 1.4f);
                doc1.Add(parag);
                parag = new Paragraph();
                parag.SetLeading(1f, 1f);
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(1, 5);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.6f);
                parag.Add(new Chunk("资料审核人签名：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    日期：      年    月    日", Font10));
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.6f);
                parag.Add(new Chunk("发放 E-Key 编号：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 65).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.6f);
                parag.Add(new Chunk("受托办理人签名：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    日期：      年    月    日", Font10));
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                // 协议页
                doc1.NewPage();
                doc1.Add(new Paragraph("山东省建设工程招标投标监管信息系统", Font12));
                parag = new Paragraph("个 人 数 字 证 书 及 电 子 印 章 使 用 协 议", Font16);
                parag.Alignment = Element.ALIGN_CENTER;
                doc1.Add(parag);
                parag = new Paragraph(" ", Font10);
                doc1.Add(parag);
                parag = new Paragraph("甲方：" + EI.Name, Font12Bold);
                doc1.Add(parag);
                parag = new Paragraph();
                parag.SetLeading(-12f, 1.0f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, "　", 24).ToString() + "乙方：青岛福莱易通软件有限公司", Font12Bold));
                //parag = new Paragraph("乙方：青岛福莱易通软件有限公司", Font12Bold);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);

                using (StreamReader sr1 = new StreamReader(File.OpenRead(AppDomain.CurrentDomain.BaseDirectory + "LoadFiles\\psnagreement.txt")))
                {
                    while (sr1.Peek() >= 0)
                    {
                        parag = new Paragraph();
                        parag.SetLeading(-1f, 1.0f);
                        parag.Add(new Chunk(sr1.ReadLine(), Font10));
                        doc1.Add(parag);
                    }
                }

                doc1.NewPage();

                #region 所需材料
                parag = new Paragraph(" ", Font16);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font16);
                doc1.Add(parag);
                parag = new Paragraph("个人申办数字证书所需递交（寄送）材料：", Font16);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("1、《个人数字证书申请表》及《个人数字证书使用协议》", Font14);
                doc1.Add(parag);
                parag = new Paragraph("   （盖章、签字、一式两份）", Font14);
                doc1.Add(parag);
                parag = new Paragraph("2、居民身份证复印件（正反面）", Font14);
                doc1.Add(parag);
                parag = new Paragraph("3、造价人员需提交“业务水平等级证书”复印件", Font14);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font16);
                doc1.Add(parag);
                parag = new Paragraph("用户可自行选择网上支付或银行汇款，支付办理费用", new Font(bfChinese, 16, Font.ITALIC));
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("汇款信息", Font16);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("名  称：青岛福莱易通软件有限公司", Font14);
                doc1.Add(parag);
                parag = new Paragraph("开户行：交行青岛宁夏路第一支行", Font14);
                doc1.Add(parag);
                parag = new Paragraph("账  号：37200 5522 0180 1004 4812", Font14);
                doc1.Add(parag);
                #endregion 所需材料

                doc1.Close();
                return Memory.GetBuffer();
            }
        }

        /// <summary>
        /// 个人Key申请表下载
        /// </summary>
        /// <param name="empGuid"></param>
        /// <returns></returns>
        public override byte[] GetPsnKeyPdf(Guid empGuid)
        {
            var EI = dbContext.Emp_Manager.FirstOrDefault(m => m.EmpGuid == empGuid);
            var Titles = dbContext.Emp_Qualities.Where(q => q.EmpGuid == empGuid && (q.IsDel == false || q.IsDel == null));
            if (EI == null || Titles == null)
            {
                return null;
            }
            Document doc1 = new Document(PageSize.A4, 60, 60, 20, 40);
            using (MemoryStream Memory = new MemoryStream())
            {
                PdfWriter PdfWriter = PdfWriter.GetInstance(doc1, Memory);

                BaseFont bfChinese = BaseFont.CreateFont(@"C:\windows\fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font Font22 = new Font(bfChinese, 22);
                Font Font18 = new Font(bfChinese, 18);
                Font Font16 = new Font(bfChinese, 16);
                Font Font14 = new Font(bfChinese, 14);
                Font Font12 = new Font(bfChinese, 12);
                Font Font12Bold = new Font(bfChinese, 12, Font.BOLD);
                Font Font10 = new Font(bfChinese, 10);
                Font Font12Italic = new Font(bfChinese, 12, Font.BOLDITALIC);
                Font Font10Bold = new Font(bfChinese, 10, Font.BOLD);
                Paragraph parag;
                Phrase phrase;
                Chunk chunk;

                doc1.Open();
                doc1.AddAuthor("青岛福莱易通软件有限公司 http://www.flyedt.com");
                doc1.AddTitle(EI.Name + " 数字证书申请表");
                doc1.Add(new Paragraph("山东省建设工程招标投标监管信息系统", Font12));
                parag = new Paragraph("个 人 Key 申 请 表", Font18);
                parag.Alignment = Element.ALIGN_CENTER;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(25f, 1f);
                parag.Add(new Chunk("以下信息由申请人填写  ", Font12Italic));
                parag.Add(new Chunk("请用签字笔如实、准确、清楚地填写，并本人签字", new Font(bfChinese, 8)));
                parag.Add(new Chunk("      " + DateTime.Now.ToLongDateString(), Font12));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(1f, 1f);
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(1, 5);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                #region 个人信息

                parag = new Paragraph();
                parag.SetLeading(5f, 1.5f);
                parag.Add(new Chunk("姓  名：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 20).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  性  别：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 5).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  出生日期：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 20).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 11).ToString() + EI.Name, new Font(bfChinese, 12)));//"赵钱孙里"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 41).ToString() + (EI.Sex == 0 ? "女" : "男"), Font12));
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 60).ToString() + (EI.Birthday.HasValue ? EI.Birthday.Value.ToString("yyyy-MM-dd") : ""), Font12));//"2002年11月12日"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1.5f);
                parag.Add(new Chunk("手  机：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 10).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  电  话：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 13).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  电子邮箱：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 27).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 9).ToString() + EI.MobileTel, new Font(bfChinese, 10)));//13355555555
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 33).ToString() + EI.Tel, Font10));//"0564 87651463"
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 62).ToString() + EI.EMail, Font10));//ayayayaya.bongbong@sina.com.cn
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1.5f);
                parag.Add(new Chunk("证件类型：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    证件号码：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 12).ToString() + GetIdType(EI.IDType), Font12));//有关部门工作证
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(-18f, 1.5f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 52).ToString() + EI.IDCard, Font12));//"370202234567890078X"
                doc1.Add(parag);

                #endregion 个人信息

                parag = new Paragraph(new StringBuilder().Insert(0, "- ", 45).ToString().Trim(), Font10Bold);

                #region 受托办理人
                parag = new Paragraph("申请人委托以下人员办理个人Key事宜（请手工填写）", new Font(bfChinese, 12, Font.BOLD));
                parag.SetLeading(5f, 1.4f);
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1.6f);
                parag.Add(new Chunk("受托办理人：", new Font(bfChinese, 10, Font.BOLD)));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 12).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  证件类型：", new Font(bfChinese, 10, Font.BOLD)));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 12).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("  证件号码：", new Font(bfChinese, 10, Font.BOLD)));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);
                #endregion 受托办理人

                #region 签字
                parag = new Paragraph(new StringBuilder().Insert(0, "- ", 45).ToString().Trim(), Font10Bold);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(5f, 1f);
                parag.Add(new Chunk(new StringBuilder().Insert(0, " ", 30).ToString() + "申请人签字：", Font16));
                doc1.Add(parag);
                #endregion 签字

                parag = new Paragraph("以下信息由Key发放点填写", Font12Italic);
                parag.SetLeading(25f, 1.4f);
                doc1.Add(parag);
                parag = new Paragraph();
                parag.SetLeading(1f, 1f);
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(1, 5);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.6f);
                parag.Add(new Chunk("资料审核人签名：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    日期：      年    月    日", Font10));
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.6f);
                parag.Add(new Chunk("发放 E-Key 编号：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 65).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                parag = new Paragraph();
                parag.SetLeading(4f, 1.6f);
                parag.Add(new Chunk("受托办理人签名：", Font10));
                chunk = new Chunk(new StringBuilder().Insert(0, " ", 30).ToString(), Font10);
                chunk.SetUnderline(0, -2);
                parag.Add(chunk);
                parag.Add(new Chunk("    日期：      年    月    日", Font10));
                parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
                doc1.Add(parag);

                #region 所需材料
                parag = new Paragraph(" ", Font10);
                doc1.Add(parag);
                parag = new Paragraph("个人申办Key所需递交（寄送）材料：", Font14);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font10);
                doc1.Add(parag);
                parag = new Paragraph("1、《个人Key申请表》（本人签字、一式两份）", Font14);
                doc1.Add(parag);
                parag = new Paragraph("2、居民身份证复印件（正反面）", Font12);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font10);
                doc1.Add(parag);
                parag = new Paragraph("用户可自行选择网上支付或银行汇款，支付办理费用", new Font(bfChinese, 12, Font.ITALIC));
                doc1.Add(parag);
                parag = new Paragraph(" ", Font10);
                doc1.Add(parag);
                parag = new Paragraph("汇款信息", Font14);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font10);
                doc1.Add(parag);
                parag = new Paragraph("名  称：青岛福莱易通软件有限公司", Font12);
                doc1.Add(parag);
                parag = new Paragraph("开户行：交行青岛宁夏路第一支行", Font12);
                doc1.Add(parag);
                parag = new Paragraph("账  号：37200 5522 0180 1004 4812", Font12);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("联系方式", Font16);
                doc1.Add(parag);
                parag = new Paragraph(" ", Font12);
                doc1.Add(parag);
                parag = new Paragraph("地  址：青岛市宁夏路288号 青岛软件园1号楼1702", Font14);
                doc1.Add(parag);
                parag = new Paragraph("邮  编：266071", Font14);
                doc1.Add(parag);
                parag = new Paragraph("总  机：0532 - 85871505", Font14);
                doc1.Add(parag);
                #endregion 所需材料

                doc1.Close();
                return Memory.GetBuffer();
            }
        }

        private string GetIdType(string code)
        {
            var result = from dic in dbContext.Dictionarys
                         where dic.ParentSID == "certificatetype" && (dic.IsDel == false || dic.IsDel == null) && dic.Code == code
                         select dic.Name;
            return result.FirstOrDefault() == null ? "身份证" : result.FirstOrDefault().ToString();
        }

        /// <summary>
        /// 续费验证key状态
        /// </summary>
        public override OperationResult ValidateKeyStatus(int caSubId, int dogId, string name)
        {
            OperationResult result = new OperationResult();
            var query = (from casub in dbContext.CAPayInfoSub
                         where casub.ID == caSubId && casub.Title == name
                         select casub).FirstOrDefault();
            if (query != null)
            {
                if ((query.bStatus != null && query.bStatus == 1) || query.bCAStatus == 4)
                {
                    result.Message = "已更新证书";
                    result.Result = false;
                }
                else
                {
                    string cakind = query.bCAKind;
                    if (cakind.StartsWith("C") || cakind.StartsWith("E"))
                    {
                        result = ValidateCorpKey(dogId, name);
                    }
                    else
                    {
                        result = ValidatePsnKey(dogId, name);
                    }
                    if (result.Result)
                    {
                        if ((query.bCAStatus == 3 && query.FlowCode == "0,019,029,;4000") || query.bCAStatus == 4)
                        {
                            result.Message += "|验证通过";
                            result.Result = true;
                        }
                        else
                        {
                            result.Message = "该 Key 或证书非财务确认或审核未通过";
                            result.Result = false;
                        }
                    }
                }
            }
            else
            {
                result.Message = "未注册的 Key 或证书不匹配";
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 验证企业key状态
        /// </summary>
        private OperationResult ValidateCorpKey(int dogId, string name)
        {
            OperationResult result = new OperationResult();
            result.Result = true;
            var users = dbContext.T_Sys_Users.Where(m => m.DogID == dogId && m.Name == name);
            var user = users.FirstOrDefault(m => m.RoleID == 105 || m.RoleID == 99105); // 同名先取代理单位
            if (user == null && users.Count() > 0) user = users.First();
            if (user == null)
            {
                result.Message = "未注册的 Key 或证书不匹配";
                result.Result = false;
            }
            else
            {
                result.Message = "User|" + user.UserGuid.ToString();
            }
            return result;
        }

        /// <summary>
        /// 验证人员key状态
        /// </summary>
        private OperationResult ValidatePsnKey(int dogId, string name)
        {
            OperationResult result = new OperationResult();
            result.Result = true;
            var psn = dbContext.Emp_Manager.FirstOrDefault(m => m.empdogid == dogId && m.Name == name && (m.IsDel == null || m.IsDel == false));
            if (psn == null || psn.CorpGuid == Guid.Empty)
            {
                result.Message = "未注册的 Key 或证书不匹配";
                result.Result = false;
            }
            else
            {
                var psnuser = dbContext.T_Sys_Users.FirstOrDefault(m => m.UserGuid == psn.CorpGuid);
                if (psnuser == null)
                {
                    result.Message = "此人员没有对应的单位";
                    result.Result = false;
                }
                else
                {
                    result.Message = "Person|" + psn.EmpGuid.ToString();
                }
            }
            return result;
        }

        /// <summary>
        /// 更新数字证书
        /// </summary>
        public override OperationResult UpdateCert(
            int caSubId,
            string Entity,
            Guid EntityGuid,
            string EntityName,
            string KeySN,
            string operation)
        {
            OperationResult result = new OperationResult();
            CA_Cert apply = new CA_Cert();
            try
            {
                String certSignBufP7 = null;//自动获取模式
                var now = DateTime.Now;

                apply.EntityType = Entity == "Person";

                //ACCOUNT_ORGANIZATION = "itruschina";
                //ACCOUNT_ORGUNIT = "ra";
                //RA_SERVICE_URL = "ica://" + System.Configuration.ConfigurationManager.AppSettings["CATestURL"].ToString() + "/version=3&characterEncoding=GBK";

                //Com.Itrus.Raapi.Result.OperationResult operationResult = JsonConvert.DeserializeObject
                //    <Com.Itrus.Raapi.Result.OperationResult>(operation);
                ItrusOperationResult operationResult = JsonConvert.DeserializeObject<ItrusOperationResult>(operation);
                ItrusPickupResult operationResult2 = JsonConvert.DeserializeObject<ItrusPickupResult>(operation);
                if (operationResult == null)
                {
                    result.Message = "-11|无法识别的请求证书";
                    result.Result = false;
                    return result;
                }
                if (!string.IsNullOrEmpty(operationResult2.CertIssuerDN) || !string.IsNullOrEmpty(operationResult2.CertIssuerHashMD5) ||
                    !string.IsNullOrEmpty(operationResult2.CertKmcRep1) || !string.IsNullOrEmpty(operationResult2.CertKmcRep2) ||
                    !string.IsNullOrEmpty(operationResult2.CertKmcRep3) || !string.IsNullOrEmpty(operationResult2.CertKmcReq2) ||
                    !string.IsNullOrEmpty(operationResult2.CertSerialNumber) || !string.IsNullOrEmpty(operationResult2.CertSignBuf) ||
                    !string.IsNullOrEmpty(operationResult2.CertSignBufP7) || !string.IsNullOrEmpty(operationResult2.CertSubjectDN) ||
                    !string.IsNullOrEmpty(operationResult2.CertSubjectHashMD5) || !string.IsNullOrEmpty(operationResult2.KmcCertSerialNumber))
                {
                    //Com.Itrus.Raapi.Result.RenewResult renewResult = (Com.Itrus.Raapi.Result.RenewResult)operationResult;
                    ItrusPickupResult pickupResult = operationResult2;
                    if (pickupResult.Success)
                    {
                        X509Certificate2 cert509 = new X509Certificate2();
                        try
                        {
                            cert509.Import(Convert.FromBase64String(pickupResult.CertSignBuf));
                        }
                        catch { }

                        #region Apply Entity
                        apply = new CA_Cert
                        {
                            CertID = Guid.NewGuid(),
                            AppID = Guid.NewGuid(),
                            AdditionalField1 = "",
                            AdditionalField2 = "",
                            AdditionalField3 = "",
                            AppDate = now,
                            CertIssued = true,
                            CertKmcSerialNumber = pickupResult.KmcCertSerialNumber ?? "",
                            CertSerialNumber = pickupResult.CertSerialNumber,
                            certSignBuf = pickupResult.CertSignBuf,
                            certSignBufKmc = "",
                            CertSignBufP7 = pickupResult.CertSignBufP7,
                            Email = "",
                            EnrollDate = now,
                            EnrollSign = "",
                            EnrollUser = "RA",
                            EntityGuid = EntityGuid,
                            EntityID = "",
                            EntityName = EntityName,
                            EntityType = apply.EntityType,
                            KeySerialNo = KeySN,
                            kmcRep1 = pickupResult.CertKmcRep1,
                            kmcRep2 = pickupResult.CertKmcRep2,
                            kmcRep3 = pickupResult.CertKmcRep3,
                            kmcReq1 = "",
                            kmcReq2 = pickupResult.CertKmcReq2 ?? "",
                            kmcReq3 = "",
                            RequestBufP7 = "",
                            Status = 0,
                            IssueDate = cert509.NotBefore,
                            ValidityTo = cert509.NotAfter,
                            VerifySign = "",
                            VerifyUser = ""
                        };
                        #endregion Apply Entity

                        try
                        {
                            dbContext.caCert.Add(apply);
                            var sub = dbContext.CAPayInfoSub.Where(m => m.ID == caSubId).FirstOrDefault();
                            if (sub != null)
                            {
                                sub.bStatus = 1;
                                sub.bCAStatus = 4;
                            }
                            dbContext.SaveChanges();
                        }
                        catch (Exception err)
                        {
                            result.Message = "-3|" + err.Message + err.InnerException.Message + err.InnerException.StackTrace;
                            result.Result = false;
                            return result;
                        }
                        //Response.Write(pickupResult.Message + "okok<br>");
                        //TODO: 安装证书
                        certSignBufP7 = pickupResult.CertSignBufP7;
                        certSignBufP7 = certSignBufP7 == null ? "" : certSignBufP7;

                        result.Message = "0" + "|bufP7:" + certSignBufP7 +
                            "|kmcReq:" + pickupResult.CertKmcReq2 +
                            "|kmcRep11:" + pickupResult.CertKmcRep1 +
                            "|kmcRep22:" + pickupResult.CertKmcRep2 +
                            "|kmcRep33:" + pickupResult.CertKmcRep3 +
                            "|certSignBuf1:" + pickupResult.CertSignBuf;
                        result.Result = true;
                    }
                    else
                    {
                        result.Message = "-3|" + pickupResult.Message + pickupResult.ExtMessage + pickupResult.BaseMessage;
                        result.Result = false;
                    }
                    return result;
                }
                else
                {
                    if (operationResult.Success)
                    {
                        result.Message = "10|" + operationResult.Message;
                        result.Result = true;
                    }
                    else
                    {
                        result.Message = "-10|" + operationResult.Message;
                        result.Result = false;
                    }
                    return result;
                }
                //else
                //{
                //    result.Message = "5|" + typeof(Com.Itrus.Raapi.Result.PickupResult).ToString();
                //    result.Result = false;
                //    return result;
                //}
            }
            catch (Exception err)
            {
                result.Message = "-1|" + err.Message;
                result.Result = false;
                return result;
            }
        }

        /// <summary>
        /// 财务确认订单
        /// </summary>
        public override OperationResult VerifyOrder(List<Guid> orderGuid, Guid userGuid)
        {
            OperationResult result = new OperationResult();
            foreach (var guid in orderGuid)
            {
                //Guid guid = orderGuid[0];
                var delOrder = from ca in dbContext.CAPayInfo
                               where ca.KeyGUID == guid
                               select ca;
                RN.ERP.Entity.ZBDLRY.tb_CAPayInfo caPayInfo = delOrder.FirstOrDefault();
                if (caPayInfo != null)
                {
                    var isAudit = (from pro in dbContext.ProductInfo
                                   join sub in dbContext.CAPayInfoSub on pro.Code equals sub.bCAKind
                                   join capay in dbContext.CAPayInfo on sub.treeID equals capay.ID
                                   where capay.AreaCode.StartsWith("06") && capay.KeyGUID == guid && (sub.bCAKind.Contains("C") || sub.bCAKind.Contains("E"))
                                   && (capay.GroupCode == "CA01" || capay.GroupCode == "CA02")
                                   select pro.IsAudit).FirstOrDefault();
                    if ((caPayInfo.bCAStatus == 2 || caPayInfo.bCAStatus == 3) && !caPayInfo.FlowCode.Contains("4001"))
                    {
                        caPayInfo.bCAStatus = 3;
                        caPayInfo.FlowCode = (isAudit != null && isAudit == true) ? "0,019,029,;4001" : "0,019,029,;4000";
                        caPayInfo.RightCode = 1;
                        caPayInfo.OptDate = DateTime.Now;
                        var list = dbContext.CAPayInfoSub.Where(c => c.treeID == caPayInfo.ID && (c.IsDel == false || c.IsDel == null)).ToList();
                        foreach (var item in list)
                        {
                            item.bCAStatus = 3;
                            item.FlowCode = (isAudit != null && isAudit == true) ? "0,019,029,;4001" : "0,019,029,;4000";
                            item.btype = 0;
                            item.RightCode = 1;
                        }
                        dbContext.SaveChanges();
                        #region 添加操作日志
                        UserLogManager.Log(new User_Log()
                        {
                            Content = "审核订单",
                            ObjectId = guid.ToString(),
                            IsrtUser = userGuid.ToString(),
                            //IsrtUserName = "",
                            //IsrtUserArea = "",
                            FunctionId = "CA",
                            FunctionType = ((int)DTO.FuncType.Verify).ToString(),
                            IsrtDate = DateTime.Now
                            //AppId = ""
                        });
                        #endregion
                        result.Result = true;
                        result.Message = "审核成功！";
                    }
                    else if (caPayInfo.FlowCode.Contains("4001"))
                    {
                        result.Result = false;
                        result.Message = "订单已审核，等待主管审核！";
                    }
                    else
                    {
                        result.Result = false;
                        result.Message = "订单未提交，不可审核！";
                    }
                }
                else
                {
                    result.Result = false;
                    result.Message = "审核失败！";
                }
            }
            return result;
        }

        public override List<DTO.tb_ProductGroupInfo> GetProductGroup()
        {
            var query = from info in dbContext.GroupInfo
                        where (info.IsDel == false || info.IsDel == null)
                        select new DTO.tb_ProductGroupInfo
                        {
                            Id = info.Id,
                            Code = info.Code,
                            IsDel = info.IsDel,
                            GroupName = info.GroupName
                        };
            return query.OrderBy(m => m.Id).ToList();
        }

        /// <summary>
        /// 获取用户已购买或可升级的产品列表
        /// </summary>
        public override List<DTO.tb_ProductInfo> GetProductsByUserGuid(string userGuid, string areacode, int type)
        {
            Guid UserGuid = Guid.Empty;
            int empid = 0;
            if (Guid.TryParse(userGuid, out UserGuid))//获取企业已有产品
            {
                var capayinfo = from cainfo in dbContext.CAPayInfo
                                join casub in dbContext.CAPayInfoSub on cainfo.ID equals casub.treeID
                                join pro in dbContext.ProductInfo on casub.bCAKind equals pro.Code
                                where (cainfo.GroupCode == "CA01" || cainfo.GroupCode == "CA04") && cainfo.CorpUserGuid == UserGuid &&
                                (cainfo.IsDel == false || cainfo.IsDel == null) && (casub.IsDel == false || casub.IsDel == null) && cainfo.bCAStatus == 4
                                && (casub.bCAKind.Contains("C") || casub.bCAKind.Contains("E")) && (string.IsNullOrEmpty(pro.AreaCode) || pro.AreaCode.StartsWith
                                (areacode.Substring(0, 2)))
                                select pro;
                if (capayinfo.Count() > 0)
                {
                    string cakind = capayinfo.OrderByDescending(m => m.Fee).FirstOrDefault().Code;
                    var query = from product in dbContext.ProductInfo
                                join proupdate in dbContext.ProductUpdateInfo on product.Code equals proupdate.Code into carelas
                                from cainrela in carelas.DefaultIfEmpty()
                                where (string.IsNullOrEmpty(product.AreaCode) || product.AreaCode.StartsWith(areacode.Substring(0, 2)))
                                //&& (product.IsDel == false || product.IsDel == null)
                                select new DTO.tb_ProductInfo
                                {
                                    Id = product.Id,
                                    KeyGuid = product.KeyGuid,
                                    ProductCode = cainrela.FormerCode,
                                    Title = product.Title,
                                    Code = product.Code,
                                    Description = product.Description,
                                    ValidateTo = product.ValidateTo,
                                    IsrtDate = product.IsrtDate,
                                    Roles = product.Roles,
                                    Fee = product.Fee,
                                    YearlyFee = product.YearlyFee,
                                    FeeDescription = product.FeeDescription,
                                    IsDel = product.IsDel,
                                    GroupCode = product.GroupCode,
                                    AreaCode = product.AreaCode,
                                    SumPay = cainrela.SumPay
                                };
                    if (type == 1)//获取企业已有产品
                    {
                        List<DTO.tb_ProductInfo> list = new List<DTO.tb_ProductInfo>();
                        if (query.Where(m => m.Code == cakind).Count() > 0)
                        {
                            list.Add(query.Where(m => m.Code == cakind).First());
                        }
                        return list;
                    }
                    else//获取企业可升级产品
                    {
                        query = query.Where(m => m.ProductCode == cakind);
                        return query.ToList();
                    }
                }
                else
                {
                    return null;
                }
            }
            else if (int.TryParse(userGuid, out empid))//获取人员已有产品
            {
                var capayinfo = from cainfo in dbContext.CAPayInfo
                                join casub in dbContext.CAPayInfoSub on cainfo.ID equals casub.treeID
                                join product in dbContext.ProductInfo on casub.bCAKind equals product.Code
                                where (cainfo.GroupCode == "CA01") && casub.SourceID == empid &&
                                (cainfo.IsDel == false || cainfo.IsDel == null) && (casub.IsDel == false || casub.IsDel == null) && cainfo.bCAStatus == 4
                                && (casub.bCAKind.Contains("D") || casub.bCAKind.Contains("F"))
                                select new DTO.tb_ProductInfo
                                 {
                                     Id = product.Id,
                                     KeyGuid = product.KeyGuid,
                                     ProductCode = product.ProductCode,
                                     Title = product.Title,
                                     Code = product.Code,
                                     Description = product.Description,
                                     ValidateTo = product.ValidateTo,
                                     IsrtDate = product.IsrtDate,
                                     Roles = product.Roles,
                                     Fee = product.Fee,
                                     YearlyFee = product.YearlyFee,
                                     FeeDescription = product.FeeDescription,
                                     IsDel = product.IsDel,
                                     GroupCode = product.GroupCode,
                                     AreaCode = product.AreaCode
                                 };
                return capayinfo.ToList();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 烟台主管审核订单
        /// </summary>
        public override OperationResult OrderAudit(List<Guid> orderGuid, Guid userGuid)
        {
            OperationResult result = new OperationResult();
            foreach (var guid in orderGuid)
            {
                //Guid guid = orderGuid[0];
                var delOrder = from ca in dbContext.CAPayInfo
                               where ca.KeyGUID == guid
                               select ca;
                RN.ERP.Entity.ZBDLRY.tb_CAPayInfo caPayInfo = delOrder.FirstOrDefault();
                if (caPayInfo != null)
                {
                    if (caPayInfo.FlowCode == "0,019,029,;4001")
                    {
                        caPayInfo.FlowCode = "0,019,029,;4000";
                        caPayInfo.OptDate = DateTime.Now;
                        var list = dbContext.CAPayInfoSub.Where(c => c.treeID == caPayInfo.ID && (c.IsDel == false || c.IsDel == null)).ToList();
                        foreach (var item in list)
                        {
                            item.FlowCode = "0,019,029,;4000";
                        }
                        dbContext.SaveChanges();
                        #region 添加操作日志
                        UserLogManager.Log(new User_Log()
                        {
                            Content = "主管审核订单",
                            ObjectId = guid.ToString(),
                            IsrtUser = userGuid.ToString(),
                            //IsrtUserName = "",
                            //IsrtUserArea = "",
                            FunctionId = "CA",
                            FunctionType = ((int)DTO.FuncType.Audit).ToString(),
                            IsrtDate = DateTime.Now
                            //AppId = ""
                        });
                        #endregion
                        result.Result = true;
                        result.Message = "审核成功！";
                    }
                    else
                    {
                        result.Result = false;
                        result.Message = "订单已审核！";
                    }
                }
                else
                {
                    result.Result = false;
                    result.Message = "审核失败！";
                }
            }
            return result;
        }

        public override List<DTO.ZBTenderPay> GetZBPayList(IList<QueryZBTenderInfoCondition> queryCondition, int pageCount, int pageSize)
        {
            var query = GetZBPay();
            query = query.BuildCondition<ZBTenderPay>(queryCondition).OrderBy(m => m.FinanceProcessed).ThenByDescending(m => m.OptDate);
            if (pageSize > 0)
            {
                query = query.Skip(pageCount * pageSize).Take(pageSize);
            }
            var list = query.ToList();
            list.ForEach(m =>
            {
                if (!string.IsNullOrEmpty(m.BankName) && string.IsNullOrEmpty(m.BankAccName)) m.BankAccName = m.CorpName;
            });
            return list;
        }

        public override string GetZBPayCount(IList<QueryZBTenderInfoCondition> queryCondition)
        {
            var query = GetZBPay();
            query = query.BuildCondition<ZBTenderPay>(queryCondition);
            string sumPay = query.Sum(m => m.PayMoney).ToString();
            string sumOut = query.Sum(m => m.PayOut).ToString();
            return query.Count().ToString() + "&" + sumPay + "&" + sumOut;
        }

        private IQueryable<DTO.ZBTenderPay> GetZBPay()
        {
            string[] strs = { "105", "99105" };
            var query = from tend in dbContext.TenderPayHistory
                        join proj in dbContext.ProjectInfo on tend.DueId equals proj.ID into tendproj
                        from tendprojs in tendproj.DefaultIfEmpty()
                        join dl in dbContext.Corp_CompanyInfos on tendprojs.Corp_dlID equals dl.dogid into projcorp
                        from projcorps in projcorp.DefaultIfEmpty()
                        join bm in dbContext.Corp_CompanyInfos on tend.CorpUserGuid equals bm.CorpUserGuid into tendcorp
                        from tendcorps in tendcorp.DefaultIfEmpty()
                        join area in dbContext.AreaInfo on tendprojs.AreaCode.Substring(0, 2) equals area.Code into areas
                        from areainfo in areas.DefaultIfEmpty()
                        where strs.Contains(projcorps.Type) && tend.Status == 1 && tend.PayType == 10
                        select new DTO.ZBTenderPay
                        {
                            ID = tend.Id,
                            FinanceProcessed = tend.FinanceProcessed,
                            FinanceRemark = tend.FinanceRemark,
                            BankName = projcorps.BankName,
                            BankAccNo = projcorps.BankAccNo,
                            BankAccName = projcorps.BankAccName,
                            Title = areainfo.Title,
                            OrderId = tend.OrderId,
                            CorpName = projcorps.CorpName,
                            DueId = tend.DueId,
                            ProjectName = tendprojs.ProjectName,
                            CorpName1 = tendcorps.CorpName,
                            PayMoney = tend.PayMoney,
                            PayOut = tend.PayMoney > 150 ? tend.PayMoney - 150 : 0,
                            OptDate = tend.OptDate,
                            OptDate1 = tend.OptDate,
                            Title1 = areainfo.Title,
                            AreaCode = tendprojs.AreaCode
                        };
            return query;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">0:转账1：开票</param>
        public override OperationResult PaySaveZBRemark(int ID, bool Processed, string Remark, int type)
        {
            OperationResult ret = new OperationResult();
            ret.Result = false;
            try
            {
                var row = dbContext.TenderPayHistory.FirstOrDefault(m => m.Id == ID);
                if (row == null)
                {
                    ret.Message = "未找到记录";
                }
                else
                {
                    string remark = row.FinanceRemark;
                    if (!string.IsNullOrEmpty(remark))
                    {
                        string[] strs = remark.Split('&');
                        if (strs.Length == 2)
                        {
                            row.FinanceRemark = type == 0 ? Remark + "&" + strs[1] : strs[0] + "&" + Remark;
                        }
                        else
                        {
                            row.FinanceRemark = Remark;
                        }
                    }
                    else
                    {
                        row.FinanceRemark = type == 0 ? Remark + "&" : "&" + Remark;
                    }
                    if (type == 0)
                    {
                        row.FinanceProcessed = Processed;
                    }
                    dbContext.SaveChanges();
                    ret.Result = true;
                }
            }
            catch (Exception err)
            {
                ret.Message = err.Message;
            }
            return ret;
        }

        public override OperationResult GetZBRemark(int ID, int type)
        {
            OperationResult ret = new OperationResult();
            ret.Result = false;
            try
            {
                var row = dbContext.TenderPayHistory.FirstOrDefault(m => m.Id == ID);
                if (row == null)
                {
                    ret.Message = "未找到记录";
                }
                else
                {
                    string remark = row.FinanceRemark;
                    string pro = row.FinanceProcessed != null ? row.FinanceProcessed.ToString() : "false";
                    if (!string.IsNullOrEmpty(remark))
                    {
                        string[] strs = remark.Split('&');
                        if (strs.Length == 2)
                        {
                            ret.Message = type == 0 ? strs[0] + "&" + pro.ToString() : strs[1] + "&" + pro.ToString();
                        }
                        else
                        {
                            ret.Message = remark + "&" + pro.ToString();
                        }
                    }
                    ret.Result = true;
                }
            }
            catch (Exception err)
            {
                ret.Message = err.Message;
            }
            return ret;
        }

        public override List<DTO.CAPayinfo_Productinfo> GetCAInfo(string corpUserGuid)
        {
            Guid corpuserGuid = Guid.Parse(corpUserGuid);
            var query = from c in dbContext.CAPayInfo
                        join s in dbContext.CAPayInfoSub
                        on c.ID equals s.treeID
                        join p in dbContext.ProductInfo
                        on s.bCAKind equals p.Code
                        where c.CorpUserGuid == corpuserGuid
                        select new DTO.CAPayinfo_Productinfo
                        {
                            iTitle = c.iTitle,
                            AreaCode = c.AreaCode,
                            LinkPerson = c.LinkPerson,
                            SendAddress = c.SendAddress,
                            officeTel = c.officeTel,
                            mobileTel = c.mobileTel,
                            bCAStatus = c.bCAStatus,
                            SumPay = c.SumPay,
                            FlowCode = c.FlowCode,
                            RegisterDate = c.RegisterDate,
                            CAStatus = c.bCAStatus == 4 ? "已做key" : (
                                c.bCAStatus == 3 && c.FlowCode.Contains("0,019,029,") ? "财务已确认" : "等待财务确认"
                            ),
                            bCAKind = s.bCAKind,
                            SourceID = s.SourceID,
                            Title = p.Title,
                            Description = p.Description
                        };
            return query.ToList();
        }
        
        #endregion

        #region 通用订单相关
        /// <summary>
        /// 获取订单列表
        /// </summary>
        public override List<DTO.PayRelation> GetCommonOrders(
            IList<QueryCommonInvoiceCondition> queryCondition, 
            Guid userGuid, 
            int pageCount, 
            int pageSize)
        {
            var query = from pInfo in dbContext.PayInfo
                        join groupinfo in dbContext.GroupInfo on pInfo.GroupCode equals groupinfo.Code
                        join rela in dbContext.InvoiceOrderRelation on pInfo.KeyGUID equals rela.OrderGuid into relas
                        from inrela in relas.DefaultIfEmpty()
                        join invo in dbContext.Invoice on inrela.InvoiceGuid equals invo.KeyGuid into invoices
                        from invoice in invoices.DefaultIfEmpty()
                        where pInfo.CorpUserGuid == userGuid && (pInfo.IsDel == false || pInfo.IsDel == null)
                        select new DTO.PayRelation
                        {
                            ID = pInfo.ID,
                            KeyGUID = pInfo.KeyGUID,
                            iTitle = pInfo.iTitle,
                            CorpUserGuid = pInfo.CorpUserGuid,
                            AreaCode = pInfo.AreaCode,
                            LinkPerson = pInfo.LinkPerson,
                            SendAddress = pInfo.SendAddress,
                            officeTel = pInfo.officeTel,
                            mobileTel = pInfo.mobileTel,
                            postCode = pInfo.postCode,
                            RegisterDate = pInfo.RegisterDate,
                            bPayStatus = pInfo.bPayStatus,
                            Code = pInfo.Code,
                            SumPay = pInfo.SumPay,
                            GroupCode = pInfo.GroupCode,
                            FlowCode = pInfo.FlowCode,
                            GroupName = groupinfo.GroupName,
                            InvoiceGUID = invoice.KeyGuid,
                            InvoiceCode = invoice.InvoiceCode,
                            Notice = invoice.Notice,
                            InvoiceSumPay = invoice.SumPay,
                            InvoiceTitle = invoice.Title,
                            InvoiceLinkMan = invoice.LinkMan,
                            InvoiceMtel = invoice.Mtel,
                            InvoicePsCode = invoice.PsCode,
                            InvoiceSendAddress = invoice.SendAddress,
                            InvoiceTel = invoice.Tel,
                            InvoiceDate = invoice.InvoiceDate,
                            SendType = invoice.SendType,
                            TaxCode = invoice.TaxCode,
                            BankName = invoice.BankName,
                            BankCode = invoice.BankCode,
                            InvoiceOptType = invoice.InvoiceOptType,
                            InvoiceType = invoice.InvoiceType,
                            InvoiceStatus = invoice.InvoiceStatus,
                            InvoiceContent = invoice.InvoiceTitle,
                            CurrentAreaCode = pInfo.CurrentAreaCode,
                            AppID = pInfo.AppID
                        };
            query = query.BuildCondition<PayRelation>(queryCondition).OrderByDescending(m => m.InvoiceGUID)
                     .ThenBy(m => m.GroupCode).ThenByDescending(m => m.ID);
            if (pageSize > 0)
            {
                query = query.Skip(pageCount * pageSize).Take(pageSize);
            }
            var list = query.ToList();
            foreach (PayRelation item in list)
            {
                switch (item.bPayStatus.ToString())
                {
                    case "0":
                        item.StrStatus = "添加订单";
                        break;
                    case "1":
                        item.StrStatus = "提交订单";
                        break;
                    case "2":
                        item.StrStatus = "线下支付";
                        break;
                    case "3":
                        item.StrStatus = "银联支付";
                        break;
                    case "4":
                        item.StrStatus = "支付确认";
                        break;
                    default:
                        item.StrStatus = "";
                        break;
                }
            }
            return list;
        }

        /// <summary>
        /// 获取订单数量。
        /// </summary>
        public override int GetCommonOrderCount(IList<QueryCommonInvoiceCondition> queryCondition, Guid userGuid)
        {
            var query = from pInfo in dbContext.PayInfo
                        where pInfo.CorpUserGuid == userGuid && (pInfo.IsDel == false || pInfo.IsDel == null)
                        select pInfo;
            return query.BuildCondition<Entity.ZBDLRY.tb_PayInfo>(queryCondition).Count();
        }

        /// <summary>
        /// 获取订单详细信息。
        /// </summary>
        public override PayInfo GetCommonOrderInfo(string orderId)
        {
            DTO.PayInfo payDTO = new DTO.PayInfo();
            Guid orderGuid = Guid.Empty;
            if (Guid.TryParse(orderId, out orderGuid))
            {
                var query = from pInfo in dbContext.PayInfo
                            where pInfo.KeyGUID == orderGuid && (pInfo.IsDel == false || pInfo.IsDel == null)
                            select pInfo;
                Entity.ZBDLRY.tb_PayInfo payInfo = query.SingleOrDefault();
                if (payInfo != null)
                {
                    EntityHelper.ConvertEntity2OtherEntity(payInfo, payDTO);
                    int payInfoId = payInfo.ID;
                    var query1 = from pSub in dbContext.PayInfoSub
                                 join product in dbContext.ProductInfo on pSub.bKind equals product.Code
                                 where pSub.treeID == payInfoId && (pSub.IsDel == false || pSub.IsDel == null)
                                 select new DTO.PayInfoSub
                                 {
                                     ID = pSub.ID,
                                     KeyGUID = pSub.KeyGUID,
                                     treeID = pSub.treeID,
                                     Title = pSub.Title,
                                     SumPay = pSub.SumPay,
                                     SourceID = pSub.SourceID,
                                     Remark = pSub.Remark,
                                     FlowCode = pSub.FlowCode,
                                     bStatus = pSub.bStatus,
                                     Description = product.Description,
                                     bKind = pSub.bKind,
                                     bPayStatus = pSub.bPayStatus,
                                     Fee = product.Fee,
                                     YearlyFee = product.YearlyFee,
                                     FeeDescription = product.FeeDescription
                                 };
                    payDTO.PayInfoSub = query1.ToList();
                    return payDTO;
                }
            }
            return null;
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        public override DTO.OperationResult AddCommonOrder(DTO.PayInfo payInfo)
        {
            OperationResult result = new OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    Entity.ZBDLRY.tb_PayInfo tbPayInfo = new Entity.ZBDLRY.tb_PayInfo();
                    EntityHelper.ConvertEntity2OtherEntity(payInfo, tbPayInfo);
                    dbContext.PayInfo.Add(tbPayInfo);
                    dbContext.SaveChanges();

                    var pIdQuery = from pInfo in dbContext.PayInfo
                               where pInfo.KeyGUID == payInfo.KeyGUID
                               select pInfo.ID;
                    payInfo.ID = pIdQuery.FirstOrDefault();
                    switch (payInfo.GroupCode.ToUpper())
                    {
                        case "EXP":
                            result = AddCommonSubOrder(payInfo);
                            break;
                        default:
                            result = null;
                            break;
                    }
                    if (result != null && result.Result)
                    {
                        #region 添加操作日志
                        UserLogManager.Log(new User_Log()
                        {
                            Content = "添加订单",
                            ObjectId = payInfo.KeyGUID.ToString(),
                            IsrtUser = payInfo.CorpUserGuid.ToString(),
                            FunctionId = "Common",
                            FunctionType = ((int)DTO.FuncType.Add).ToString(),
                            IsrtDate = payInfo.RegisterDate
                        });
                        #endregion
                        tran.Commit();
                    }
                    else
                    {
                        tran.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    result.Message = "添加失败：" + ex.Message;
                    result.Result = false;
                    tran.Rollback();
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 添加附属支付信息
        /// </summary>
        internal DTO.OperationResult AddCommonSubOrder(PayInfo payInfo)
        {
            OperationResult result = new OperationResult();
            try
            {
                foreach (PayInfoSub item in payInfo.PayInfoSub)
                {
                    item.treeID = payInfo.ID;
                    Entity.ZBDLRY.tb_PayInfo_Sub tbPayInfoSub = new Entity.ZBDLRY.tb_PayInfo_Sub();
                    EntityHelper.ConvertEntity2OtherEntity(item, tbPayInfoSub);
                    dbContext.PayInfoSub.Add(tbPayInfoSub);
                }
                dbContext.SaveChanges();
                result.Result = true;
                result.Message = "添加成功！";
            }
            catch (Exception ex)
            {
                result.Message = "添加失败：" + ex.Message;
                result.Result = false;
            }
            return result;
        }
        
        /// <summary>
        /// 修改订单
        /// </summary>
        public override OperationResult EditCommonOrder(PayInfo payInfo)
        {
            OperationResult result = new OperationResult();
            using (DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection)
            {
                con.Open();
                DbTransaction tran = con.BeginTransaction();
                try
                {
                    var pay = dbContext.PayInfo.Where(c => c.KeyGUID == payInfo.KeyGUID).SingleOrDefault();
                    if (pay != null)
                    {
                        if (pay.bPayStatus == 0)
                        {
                            pay.OptDate = payInfo.OptDate;
                            pay.SumPay = payInfo.SumPay;
                            var newList = payInfo.PayInfoSub;
                            var oldList = dbContext.PayInfoSub.Where(c => c.treeID == pay.ID).ToList();
                            for (int i = 0; i < newList.Count; i++)
                            {
                                for (int j = 0; j < oldList.Count; j++)
                                {
                                    if (newList[i].SourceID == oldList[j].SourceID)////更新
                                    {
                                        oldList[j].SumPay = newList[i].SumPay;
                                        oldList[j].bKind = newList[i].bKind;
                                        oldList[j].IsDel = false;
                                        break;
                                    }
                                    else if (j == oldList.Count - 1)////新增
                                    {
                                        newList[i].treeID = pay.ID;
                                        Entity.ZBDLRY.tb_PayInfo_Sub tbPayInfoSub = new Entity.ZBDLRY.tb_PayInfo_Sub();
                                        EntityHelper.ConvertEntity2OtherEntity(newList[i], tbPayInfoSub);
                                        dbContext.PayInfoSub.Add(tbPayInfoSub);
                                    }
                                }
                            }
                            
                            ////删除子订单
                            oldList.ForEach(ps => 
                            {
                                if (!newList.Exists(p => p.SourceID == ps.SourceID))
                                {
                                    ps.IsDel = true;
                                }
                            });

                            dbContext.SaveChanges();
                            #region 添加操作日志
                            UserLogManager.Log(new User_Log()
                            {
                                Content = "修改订单",
                                ObjectId = payInfo.KeyGUID.ToString(),
                                IsrtUser = pay.CorpUserGuid.ToString(),
                                FunctionId = "Common",
                                FunctionType = ((int)DTO.FuncType.Edit).ToString(),
                                IsrtDate = payInfo.OptDate
                            });
                            #endregion
                            result.Result = true;
                            result.Message = "修改成功！";
                            tran.Commit();
                        }
                        else
                        {
                            result.Result = false;
                            result.Message = "已提交订单不可修改！";
                        }
                    }
                    else
                    {
                        result.Result = false;
                        result.Message = "修改失败！";
                    }
                }
                catch (Exception ex)
                {
                    result.Message = "修改失败：" + ex.Message;
                    result.Result = false;
                    tran.Rollback();
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <returns></returns>
        public override OperationResult DeleteCommonOrder(Guid orderGuid)
        {
            OperationResult result = new OperationResult();
            var delOrder = from pInfo in dbContext.PayInfo
                           where pInfo.KeyGUID == orderGuid
                           select pInfo;
            Entity.ZBDLRY.tb_PayInfo payInfo = delOrder.FirstOrDefault();
            if (payInfo != null)
            {
                if (payInfo.bPayStatus == 0)
                {
                    payInfo.IsDel = true;
                    dbContext.PayInfoSub.Where(c => c.treeID == payInfo.ID && (c.IsDel == false || c.IsDel == null))
                        .ToList().ForEach(s=>s.IsDel=true);
                    
                    dbContext.SaveChanges();

                    #region 添加操作日志
                    UserLogManager.Log(new User_Log()
                    {
                        Content = "删除订单",
                        ObjectId = orderGuid.ToString(),
                        IsrtUser = payInfo.CorpUserGuid.ToString(),
                        FunctionId = "Common",
                        FunctionType = ((int)DTO.FuncType.Del).ToString(),
                        IsrtDate = DateTime.Now
                    });
                    #endregion
                    result.Result = true;
                    result.Message = "删除成功！";
                }
                else
                {
                    result.Result = false;
                    result.Message = "已提交订单不可删除！";
                }
            }
            else
            {
                result.Result = false;
                result.Message = "删除失败！";
            }
            return result;
        }

        /// <summary>
        /// 生成订单。
        /// </summary>
        /// <returns></returns>
        public override OperationResult SubmitCommonOrder(PayInfo payInfo)
        {
            OperationResult result = new OperationResult();
            try
            {
                var pay = dbContext.PayInfo.Where(c => c.KeyGUID == payInfo.KeyGUID).SingleOrDefault();
                if (pay != null)
                {
                    if (pay.bPayStatus == 0 || pay.bPayStatus == 1)
                    {
                        pay.iTitle = payInfo.iTitle;
                        pay.LinkPerson = payInfo.LinkPerson;
                        pay.SendAddress = payInfo.SendAddress;
                        pay.mobileTel = payInfo.mobileTel;
                        pay.officeTel = payInfo.officeTel;
                        pay.postCode = payInfo.postCode;
                        pay.bPayStatus = payInfo.bPayStatus;
                        pay.Notice = payInfo.Notice;
                        pay.TransDate = DateTime.Now;
                        pay.OptDate = payInfo.OptDate;
                        var list = dbContext.PayInfoSub.Where(c => c.treeID == pay.ID && (c.IsDel == false || c.IsDel == null)).ToList();
                        foreach (var item in list)
                        {
                            item.bPayStatus = payInfo.bPayStatus;
                        }
                        dbContext.SaveChanges();
                        #region 添加操作日志
                        UserLogManager.Log(new User_Log()
                        {
                            Content = pay.bPayStatus == 1 ? "银联支付" : "线下支付",
                            ObjectId = payInfo.KeyGUID.ToString(),
                            IsrtUser = pay.CorpUserGuid.ToString(),
                            FunctionId = "CA",
                            FunctionType = ((int)DTO.FuncType.SubmitOrder).ToString(),
                            IsrtDate = payInfo.OptDate
                        });
                        #endregion
                        result.Result = true;
                        result.Message = "提交成功！";
                    }
                    else
                    {
                        result.Message = "该订单不可再次提交！";
                        result.Result = false;
                    }
                }
                else
                {
                    result.Message = "提交失败！";
                    result.Result = false;
                }
            }
            catch (Exception ex)
            {
                result.Message = "提交失败：" + ex.Message;
                result.Result = false;
            }
            return result;
        }

        /// <summary>
        /// 获取做key信息列表
        /// </summary>
        public override List<DTO.tb_CAPayInfo_DogID> GetMakeKeyInfos(MakeKeyInfosCondition condition, int pageIndex, int pageSize, out int count)
        {
            count = 0;
            string areacode = ConfigurationManager.AppSettings["Area"];
            var query = from pInfo in dbContext.CAPayInfo
                        join user in dbContext.T_Sys_Users on pInfo.CorpUserGuid equals user.UserGuid
                        join  pSub in dbContext.CAPayInfoSub on pInfo.ID equals pSub.treeID
                        join area in dbContext.AreaSubInfo on pInfo.AreaCode equals area.SortCode
                        where pSub.bCAKind == "F10" && (pInfo.IsDel == false || pInfo.IsDel == null) && area.Code == areacode  
                        select new DTO.tb_CAPayInfo_DogID
                        {
                            ID = pInfo.ID,
                            KeyGUID = pInfo.KeyGUID,
                            iTitle = pInfo.iTitle,
                            CorpUserGuid = pInfo.CorpUserGuid,
                            AreaCode = pInfo.AreaCode,
                            AreaCodeName=area.Title,
                            LinkPerson = pInfo.LinkPerson,
                            SendAddress = pInfo.SendAddress,
                            officeTel = pInfo.officeTel,
                            mobileTel = pInfo.mobileTel,                           
                            RegisterDate = pInfo.RegisterDate,
                            bCAStatus = pInfo.bCAStatus,
                            FlowCode = pInfo.FlowCode,
                            Code = pInfo.Code,
                            SumPay = pInfo.SumPay,
                            GroupCode = pInfo.GroupCode,                          
                            CurrentAreaCode = pInfo.CurrentAreaCode,
                            DogID=user.DogID
                        };
            if (!string.IsNullOrEmpty(condition.AreaCode) && (condition.AreaCode!="-1"))
            {
                query = query.Where(r => r.AreaCode == condition.AreaCode);
            }
             if (!string.IsNullOrEmpty(condition.CorpName))
            {
                query = query.Where(r => r.iTitle.Contains(condition.CorpName.Trim()));
            }
             if (condition.MakeStatus>0)
             {
                 if(condition.MakeStatus==1)
                   query = query.Where(r => r.DogID>0);
                 else
                   query = query.Where(r => r.DogID==-1);
             }
            query = query.OrderBy(m => m.iTitle)
                     .ThenBy(m => m.AreaCode).ThenBy(m => m.ID);

            count = query.Count();
            if (pageSize > 0)
            {
                query = query.Skip(pageIndex * pageSize).Take(pageSize);
            }
            var list = query.ToList();           
            return list;
        }

        /// <summary>
        /// 获取支付的订单列表
        /// </summary>
        /// <returns></returns>
        public override StatisticsStruct GetPaidOrderList(string orderID, DateTime? startTime, DateTime? endTime)
        {
            StatisticsStruct list = new StatisticsStruct();
            ////取得全部数据源
            var query = from pay in dbContext.PayInfo
                         join sub in dbContext.PayInfoSub
                         on pay.ID equals sub.treeID
                         where sub.bPayStatus == 3
                         select new StatisticsOrder1 
                         { 
                             OrderID = pay.Code, 
                             Name = pay.LinkPerson, 
                             OptDate = pay.OptDate 
                         };

            if (!String.IsNullOrEmpty(orderID))
            {
                query = query.Where(o => o.OrderID == orderID);
            }
            if (startTime != null)
            {
                query = query.Where(o => o.OptDate > startTime);
            }
            if (endTime != null)
            {
                query = query.Where(o => o.OptDate < endTime);
            }

            List<StatisticsOrder1> source = query.ToList();
            ////1、标题
            StatisticsStruct.StatisticsHeader header = new StatisticsStruct.StatisticsHeader();
            StatisticsStruct.StatisticsCell hcell1 = new StatisticsStruct.StatisticsCell { Value = "订单号" };
            StatisticsStruct.StatisticsCell hcell2 = new StatisticsStruct.StatisticsCell { Value = "姓名" };
            StatisticsStruct.StatisticsCell hcell3 = new StatisticsStruct.StatisticsCell { Value = "支付时间" };
            List<StatisticsStruct.StatisticsCell> hcell_list = new List<StatisticsStruct.StatisticsCell>();
            hcell_list.Add(hcell1);
            hcell_list.Add(hcell2);
            hcell_list.Add(hcell3);
            header.HeaderCells = hcell_list.ToArray();
            List<StatisticsStruct.StatisticsHeader> header_list = new List<StatisticsStruct.StatisticsHeader> { header };
            list.Header = header_list.ToArray();
            
            ////2、数据
            List<StatisticsStruct.StatisticsRow> row_list = new List<StatisticsStruct.StatisticsRow>();
            source.ForEach(o => 
            {
                StatisticsStruct.StatisticsRow row = new StatisticsStruct.StatisticsRow();
                List<StatisticsStruct.StatisticsCell> cell_list = new List<StatisticsStruct.StatisticsCell>();
                StatisticsStruct.StatisticsCell cell1 = new StatisticsStruct.StatisticsCell { Value = o.OrderID };
                StatisticsStruct.StatisticsCell cell2 = new StatisticsStruct.StatisticsCell { Value = o.Name };
                StatisticsStruct.StatisticsCell cell3 = new StatisticsStruct.StatisticsCell { Value = o.OptDate == null ? "" : o.OptDate.ToString() };
                cell_list.Add(cell1);
                cell_list.Add(cell2);
                cell_list.Add(cell3);
                row.DataCells = cell_list.ToArray();
                row_list.Add(row);
            });

            list.Data = row_list.ToArray();
            return list;
        }

        /// <summary>
        /// 专家获取订单列表
        /// </summary>
        /// <returns></returns>
        public override StatisticsStruct GetOrderHistoryList(Guid userGuid)
        {
            StatisticsStruct list = new StatisticsStruct();
            ////取得全部数据源
            var query = from pay in dbContext.PayInfo
                        join sub in dbContext.PayInfoSub
                        on pay.ID equals sub.treeID
                        where sub.bPayStatus == 3
                        select new StatisticsOrder1
                        {
                            OrderID = pay.Code,
                            Name = pay.LinkPerson,
                            OptDate = pay.OptDate
                        };

            List<StatisticsOrder1> source = query.ToList();
            ////1、标题
            StatisticsStruct.StatisticsHeader header = new StatisticsStruct.StatisticsHeader("订单号", "支付时间");
            List<StatisticsStruct.StatisticsHeader> header_list = new List<StatisticsStruct.StatisticsHeader> { header };
            list.Header = header_list.ToArray();

            ////2、数据
            List<StatisticsStruct.StatisticsRow> row_list = new List<StatisticsStruct.StatisticsRow>();
            source.ForEach(o =>
            {
                StatisticsStruct.StatisticsRow row = new StatisticsStruct.StatisticsRow();
                List<StatisticsStruct.StatisticsCell> cell_list = new List<StatisticsStruct.StatisticsCell>();
                StatisticsStruct.StatisticsCell cell1 = new StatisticsStruct.StatisticsCell { Value = o.OrderID };
                StatisticsStruct.StatisticsCell cell2 = new StatisticsStruct.StatisticsCell { Value = o.OptDate == null ? "" : o.OptDate.ToString() };
                cell_list.Add(cell1);
                cell_list.Add(cell2);
                row.DataCells = cell_list.ToArray();
                row_list.Add(row);
            });

            list.Data = row_list.ToArray();
            return list;
        }
        #endregion
    }
}
